Angular 2 Set focus on first field of form on component load

Naveed Ahmed picture Naveed Ahmed · Sep 20, 2016 · Viewed 18.1k times · Source

In my app I want to automatically set focus on first field of form on component load. Can anyone please guide how to achieve this without any repetition as I want this on every form (Reactive Forms) in my app.

Answer

Rajiv picture Rajiv · Sep 7, 2017

you can achieve this by simply adding the "autofocus" attribute to your input element like.

<input class="form-control" [formControl]="name" autofocus>