To implement a directive that manages focus on dynamically added elements in Angular, use ElementRef and AfterViewInit to set focus when the element is rendered.
Auto-Focus Directive
1. Create the Directive
import { Directive, ElementRef, AfterViewInit } from '@angular/core';
@Directive({
selector: '[appAutoFocus]'
})
export class AutoFocusDirective implements AfterViewInit {
constructor(private el: ElementRef) {}
ngAfterViewInit() {
this.el.nativeElement.focus();
}
}
2. Use in Template
<input type="text" appAutoFocus />