Hi,
I want to set the focus to the first invalid control in a form. This works fine for all controls except for the dropdown list.
I've created a stackblitz fork for reproduction:
https://stackblitz.com/edit/angular-n9wue6?file=app/app.component.ts
Any ideas how I can fix this?
Thx
4 Answers, 1 is accepted
Hi Peter,
Thank you for the provided StackBlitz.
The most straight forward approach to focus the DropDownList component is to use the built-in focus method. I updated the example by adding a button which focuses the component using the suggested method:
https://stackblitz.com/edit/angular-n9wue6-cauxpn?file=app/app.component.ts
I hope this helps. Let me know if any further questions come up on this case.
Regards,
Martin
Progress Telerik
Our thoughts here at Progress are with those affected by the outbreak.
Hello Martin,
yes this works, but it's not what I need.
I little recap what I want to achieve:
1. I've got a generic form component with several controls
2. The form is only aware of a list of controls
3. In the onSubmit method the validation takes place
4. If any of the controls is invalid the form is also marked as invalid. The validation errors are displayed.
5. For better user experience I want to focus on the first invalid control
{code}
const firstElementWithError = document.querySelector('.ng-invalid') as HTMLElement;
firstElementWithError.focus();
{code}
The above code works fine for all other controls in my form except for the dropdown.
Any ideas?
Thx
Peter
Hi Peter,
Thank you for the provided additional details on this case.
To answer the question of why the code demonstrated in the initial StackBlitz example does not work with the DropDownList is because the targeted element does not receive the focus actually. target the inner span tag by adding the .k-dropdown-wrap CSS class after the custom ID in the querySelector method in order to focus the component:
ngOnInit() {
setTimeout(() => {
const control = document.querySelector(
"#notWorkingDropDownList .k-dropdown-wrap"
) as any;
control.focus();
});
}
Here is an updated example:
https://stackblitz.com/edit/angular-n9wue6-gon3bc?file=app/app.component.ts
Let me know if I can provide any further assistance for this case.
Regards,
Martin
Progress Telerik
Our thoughts here at Progress are with those affected by the outbreak.
Hi Martin,
I was hoping that I won't need this workaround but unfortunately there's no way without it. Thx for your support.
Regards,
Peter