Tim Deschryver

Auto-focus a form control with an Angular directive


In an application that has a lot of CRUD forms, it can be useful for users to give focus to a form control. It's a small thing that can improve the user experience by a lot. For example, when a modal opens and the user has to move the mouse towards the form control and click it, instead, the user can just start to type when the model is opened.

While it's possible to focus an element with the autocomplete attribute, I found that creating an Angular Directive is more convenient.

When the directive's selector is set to form, every form in the application will automatically focus the first form control. The directive below also gives focus to the form control that's invalid when the form is submitted.

Keep in mind, that giving a control auto-focus isn't always good for your users as it reduces usability and accessibility.

Please consider supporting me if have you enjoyed this post and found it useful:

Buy Me A Coffee PayPal logo
Support the blog Share on Twitter Discuss on Twitter Edit on GitHub