import { Directive, OnInit, ElementRef, Input } from '@angular/core'; @Directive({ selector: '[fbAutofocus]' }) export class FbAutofocusDirective implements OnInit { @Input() fbAutofocus: string = 'input'; @Input() disabled: boolean = false; private element: HTMLElement; constructor( private readonly elementRef: ElementRef, ) { this.element = elementRef.nativeElement; } ngOnInit(): void { if (this.disabled) { return; } const whenElementVisible: number = setInterval(() => { const visible: boolean = !!this.element.offsetParent; if (visible) { this.setFocus(); clearInterval(whenElementVisible); } }); } private setFocus(): void { if (this.fbAutofocus && this.fbAutofocus !== '' && this.fbAutofocus !== 'this') { this.getChildElementFromQuery(this.fbAutofocus); } if (!this.fbAutofocus || this.fbAutofocus === '' || this.fbAutofocus === 'this') { this.element = this.elementRef.nativeElement; } this.element.setAttribute('autofocus', ''); } private getChildElementFromQuery(elementSelector: string): void { this.element = this.elementRef.nativeElement.querySelector(elementSelector); if (this.element === null || this.element === undefined) { throw new Error( `The element was not found by your given query ${this.fbAutofocus}. If you intended to access the member you placed the directive on, use the 'this' keyword as query. Otherwise make sure the queried element exists as a child on your component` ); } } }