Auto-focus a form control with an Angular directive

Tim Deschryver

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.

Feel free to update this blog post on GitHub, thanks in advance!

Join My Newsletter (WIP)

Join my weekly newsletter to receive my latest blog posts and bits, directly in your inbox.

Support me

I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.

Buy Me a Coffee at PayPal logo

Share this post on

Twitter LinkedIn