Just a small directive that will set focus on an focusable element:
import { AfterContentInit, Directive, ElementRef, Input } from ‘@angular/core’;
export const FOCUSABLE_ELEMENTS_QUERY = ‘button, [href], input, select, textarea, [tabindex]:not([tabindex=”-1″])’;
@Directive({
selector: ‘[autoFocus]’,
})
export class AutofocusDirective implements AfterContentInit {
@Input() public appAutoFocus: boolean;
public constructor(private el: ElementRef) {}
public ngAfterContentInit() {
// We first execute setTimeout to make sure Angular has rendered the component tree.
setTimeout(() => {
if (!this.el.nativeElement) {
console.error(`Element does not have a nativeElement.`);
}
let elementToFocus: HTMLElement;
const nativeElement: HTMLElement = this.el.nativeElement as HTMLElement;
if (this.isFocusable(nativeElement)) {
elementToFocus = this.el.nativeElement;
} else {
const focusableElements = nativeElement.querySelectorAll(FOCUSABLE_ELEMENTS_QUERY);
if (focusableElements && focusableElements.length > 0) {
elementToFocus = focusableElements[0] as HTMLElement;
}
}
if (elementToFocus) {
elementToFocus.focus();
} else {
console.error(‘No focusable element found.’);
}
});
}
public isFocusable(element: HTMLElement): boolean {
const tagName = element.tagName.toLowerCase();
return (
tagName === ‘input’ ||
tagName === ‘button’ ||
tagName === ‘select’ ||
tagName === ‘textarea’ ||
element.hasAttribute(‘href’) ||
(element.hasAttribute(‘tabindex’) && element.tabIndex !== null && element.tabIndex !== –1)
);
}
}
<
p style=”background: #1e1e1e”>