Add a simple autofocus
directive
The problem with the autofocus
attribute is that it has the following behavior (see here the full source for more information about autofocus
at MDN):
The autofocus
global attribute is a Boolean attribute indicating that an element should be focused on page load, or when the <dialog>
that it is part of is displayed.
So if your button or input element is rendered at later time autofocus won't work as expected.
You can easily change this behavior by wrapping the existing attribute inside your own custom directive that will also focus on the element when it is initialized. You only need a few lines of code; mine looks like this and works well:
import { AfterViewInit, Directive, ElementRef } from '@angular/core';
// This directive makes autofocus work for form input elements that are rendered after initial page load
@Directive({
selector: 'input',
})
export class AutoFocusDirective implements AfterViewInit {
constructor(public elementRef: ElementRef) {
}
public ngAfterViewInit(): void {
if (this.elementRef.nativeElement.autofocus) {
this.elementRef.nativeElement.focus();
}
}
}
Note: Make sure you load this globally or make sure that don't forget to load the directive in your module each time you want this customized behavior, otherwise you will be banging your head against the wall wondering why it doesn't work...
cdkTrapFocus [cdkTrapFocusAutoCapture]="true"
to a div containing the button to be focused, and then addingcdkFocusInitial
to the button. also import A11yModule https://mcmap.net/q/893871/-cdkfocusinitial-attribute-not-focusing-the-dom-element – Tithonus