Reputation: 4871
In Angular 10 project, I have a form with 2 inputs named Username and Password. I am using
cdkFocusInitial
attribute on username field, however it's not focusing on page load. Here is a StackBlitz example that shows the issue https://stackblitz.com/edit/angular-4amzj4?file=src%2Fapp%2Ffocus-monitor-directives-example.html
<div class="example-focus-monitor">
<mat-form-field appearance="fill">
<mat-label>Username</mat-label>
<input cdkFocusInitial aria-label="Username" class="username" matInput placeholder="Enter Username" type="text">
</mat-form-field>
<br/>
<mat-form-field appearance="fill">
<mat-label>Password</mat-label>
<input aria-label=" Password" class="password" matInput placeholder="Enter Password" type="text">
</mat-form-field>
</div>
Upvotes: 13
Views: 25597
Reputation: 304
This is because cdkFocusInitial is used in the context of FocusTrap. You can read about it here.
For performing autofocus, you can create a directive, which will take the element's reference and focus it.
import { AfterContentInit, Directive, ElementRef, Input } from "@angular/core";
@Directive({
selector: "[autoFocus]"
})
export class AutofocusDirective implements AfterContentInit {
@Input() public appAutoFocus: boolean;
public constructor(private el: ElementRef) {}
public ngAfterContentInit() {
setTimeout(() => {
this.el.nativeElement.focus();
}, 100);
}
}
Use this directive like
<input
autoFocus
aria-label="Username"
class="username"
matInput
placeholder="Enter Username"
type="text"
>
If you use this multiple times on a page, the one where it used last will be focused. Cheers!
Upvotes: 13