Search code examples
angularangular-materialangular10

cdkFocusInitial attribute not focusing the DOM element


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>

Solution

  • Add in first div:

    cdkTrapFocus [cdkTrapFocusAutoCapture]="true" 
    

    https://stackblitz.com/edit/angular-4amzj4-nz2yh4?file=src%2Fapp%2Ffocus-monitor-directives-example.html