In Angular, you can set focus on an input field automatically on page load by using the ViewChild
decorator to get a reference to the input field in your component, and then use the focus()
method to set focus on it.
For example, let’s say we have a form in our template file which has three inputs firstName, lastName and email.
We want to set focus automatically on the firstName field as soon as the page loads.
To make that happen, the first thing we need is the reference to that input element so that we can call the focus()
method on it.
In Angular, you can give a reference to an element using the template reference variables. A template reference variable can be created by putting a hash symbol before the variable name eg. #myInput
Let’s assign a reference variable #myInput
to the very first input of our form:
<div class="container"> <form [formGroup]="userForm" > <div> <input #myInput type="text" formControlName="firstName" placeholder="Type here"> <label> First Name</label> </div> <div> <input type="text" formControlName="lastName" placeholder="Type here"> <label> Last Name</label> </div> <div> <input type="email" formControlName="email" placeholder="Type here"> <label> Email</label> </div> <button type="submit" (click)="submit()">Submit</button> </form> </div>
Now, to access the input element from our template to our ts file, we can use the @ViewChild()
decorator.
Simply pass the name of the template reference variable as an argument to the @ViewChild()
decorator to get access to the corresponding element.
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit, AfterViewInit { @ViewChild('myInput') myInput: any; userForm: FormGroup; constructor(private fb: FormBuilder) { this.userForm = this.fb.group({ firstName: ['', Validators.required], lastName: ['', Validators.required], email: ['', [Validators.required, Validators.email]] }); } ngOnInit(): void { } ngAfterViewInit(): void { // Set focus to the firstName field this.myInput.nativeElement.focus(); } submit(){ // Add your stuff } }
Output:
Please note that we have called the focus()
method inside the ngAfterViewInit()
lifecycle hook instead of ngOnInit()
hook. But why?
Here is the reason.
In Angular, the ngOnInit()
lifecycle hook is called after the component has been initialized and the input properties have been set. It’s typically used for initialization tasks that don’t require access to the DOM or child components.
On the other hand, the ngAfterViewInit()
lifecycle hook is called after the view has been initialized and the component’s children have been initialized. It’s typically used for initialization tasks that require access to the DOM or child components.
In the case of setting focus on an input field, we need access to the DOM element of the input field, which is not available in ngOnInit()
. The reason for this is that the input field may not have been created yet when ngOnInit()
is called, so we can’t access it.
By using ngAfterViewInit()
, we can be sure that the input field has been created and added to the DOM, so we can safely access it and set focus on it.
So, if you put the nativeElement.focus()
method inside the ngOnInit()
life cycle hook, you may encounter an error.
That’s all for this article. Thanks for reading!