Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 377
Naveed Ahmed Avatar asked Sep 19 '16 22:09

Naveed Ahmed


People also ask

How to focus on first field form in Angular?

Create the Angular app to be used. Create a directive “AutoFocus” that handles the auto-focus of input fields. In this directive set the HTML element as focused. Then import this directive inside app.

What is autofocus Angular?

HTML form elements already provide for an “autofocus” attribute that will pull focus to an input field after it is rendered on the page. HTML5 autofocus. The problem is when you move the one to another pages using the angular router on single page application.


2 Answers

HTML autofocus attribute do exactly that

<input type="text" name="fname" autofocus>

like image 198
Yinon Avatar answered Oct 13 '22 23:10

Yinon


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

<input class="form-control" [formControl]="name" autofocus>
like image 39
Rajiv Avatar answered Oct 13 '22 22:10

Rajiv