How to set tabindex for angular material elements?

Viewed 9988

How could I set tabindex=-1 on angular material elements? f.e. if I set it into mat-checkbox, in DOM I see:

mat-checkbox tab-index=-1
   label
      input tabindex=0

and in the mat-button-toggle the same: button inside mat-wrappera doesn't change its tab index.

2 Answers

If you want to bind the tabindex attribute of the Angular Material element, you should assign the value after rendering the element.

To make it clear, I created 2 mat-select elements and 2 properties to bind to tabindex attribute.

First property (tabindex_1) will be declared and assigned normally, the second one (tabindex_2) will be assigned inside ngAfterViewInit method.

If you open the console, you will see the element that binds tabindex_1 returned back to 0, but the second one is binded as expected.

app.component.html

<mat-form-field>
  <mat-label>Gender</mat-label>
  <mat-select [tabindex]="tabindex_1">
    <mat-option>Male</mat-option>
    <mat-option>Female</mat-option>
  </mat-select>
</mat-form-field>

<mat-form-field>
  <mat-label>Country</mat-label>
  <mat-select [tabindex]="tabindex_2">
    <mat-option>US</mat-option>
    <mat-option>UK</mat-option>
  </mat-select>
</mat-form-field>

app.component.ts

export class AppComponent implements AfterViewInit {
  // this will be ignored
  tabindex_1 = '1';
  tabindex_2;

  ngAfterViewInit(): void {
    // this will be reflected
    this.tabindex_2 = '2';
  }
}

Check this example at Stackblitz

Related