Angular is a great framework for building front-end web applications. One of its many features is the ability to set focus on input angular element. This can be useful in a variety of situations, such as when you want to focus on a particular input field after a user clicks a button.
There are a few different ways to set focus on an input angular element. One way is to using the autofocus
attribute. This is a good option if you only want to set focus on an input element once, such as when a page is first loaded. Another way is to use the nativeElement.focus()
method. This is a good option if you want to set focus on an input element dynamically, such as after a user clicks a button. Finally, you can use the @ViewChild
decorator to inject a reference to the desired input element into your component class.
All methods will work in all angular version including angular 2, angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13 and angular 14 application.
Also Read: Angular Focusout Event on Input Example
Which method you use in Angular will depend on your particular use case. In most cases, either the autofocus
attribute or the nativeElement.focus() method will be sufficient. However, if you need to set focus on an input element dynamically, the @ViewChild
decorator is the best option.
Let’s learn the all methods
Method 1 : Set Auto focus Using AotoFocus Attribute in Angular
In this method we will use AutoFocus Attribute attribute to set the focus on input element in angular as follow
<input type="text" autofocus />
Here we used autofocus
attribute to set the focus on page load in angular.
Method 2 : Set Focus using ViewChild in Angular
In this method we will use ViewChild to set the focus on input element in angular as follow
<input type="text" autofocus #search />
<button (click)='search.focus()'>Add Focus</button>
Here we used #search
and on click of button we used search.focus
to set the focus to input. By using this method we can set focus dynamically.
And if you want to set it from component
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-hello-world',
templateUrl: './hello-world.component.html',
styleUrls: ['./hello-world.component.css'],
})
export class HelloWorldComponent implements OnInit {
@ViewChild("search") search : ElementRef;
constructor() {
}
focusIn(event:any) {
this.search.nativeElement.focus();
}
ngOnInit() {}
}