Create a New Directive :
Generate a new directive using the Angular CLI :
ng generate directive autofocus
This will create a autofocus.directive.ts file and an autofocus.directive.spec.ts file
Define the Directive :
In the autofocus.directive.ts file , import the Directive and ElementRef from Angular’s core module.
Annotate the class with the Directive decorator , passing the selector as an argument. The selector can be a simple attribute, class , or element. For example , [appAutofocus].
Inject the ElementRef into the constructor to access the DOM element.
Implement the ngOnInit Lifecycle Hook :
Override the ngOnInit lifecycle hook to execute the auto-focus logic.
Inside ngOnInit , use the ElementRef to access the native DOM element.
Call the focus() method on the DOM element to set the focus.
import { Directive , ElementRef , OnInit } from '@angular/core';
@Directive ({
selector: '[appAutofocus]'
})
export class AutofocusDirective implements OnInit {
constructor (private
el: ElementRef) {}
ngOnInit() {
this.el.nativeElement.focus();
}
}
Use the Directive in Your Template :
In your component template , apply the directive to the input element you want to auto-focus.
<input type="text" appAutofocus>