I am new to Angular, and am trying to use it to set focus on an input with the id \"input1\". I am using the following code:
Here is a directive that you can use in any component:
import { NgZone, Directive, ElementRef, AfterContentInit, Renderer2 } from '@angular/core';
@Directive({
selector: '[appFocus]'
})
export class FocusDirective implements AfterContentInit {
constructor(private el: ElementRef, private zone: NgZone, private renderer: Renderer2) {}
ngAfterContentInit() {
this.zone.runOutsideAngular(() => setTimeout(() => {
this.renderer.selectRootElement(this.el.nativeElement).focus();
}, 0));
}
}
Use: