Angular Material - Know exactly which tab was selected

Actually answering myself twice because I think this solution is interesting as well, and probably closest (yet) to what I'm looking for:

View

<mat-tab-group (selectedTabChange)="onTabChange($event)">
  <mat-tab *ngIf="true" label="tab1">
    <ng-template mat-tab-label>Label 1</ng-template>
    Content 1
  </mat-tab>
  <mat-tab *ngIf="false" label="tab2">
    <ng-template mat-tab-label>Label 2</ng-template>
    Content 2
  </mat-tab>
  <mat-tab *ngIf="true" label="tab3">
    <ng-template mat-tab-label>Label 3</ng-template>
    Content 3
  </mat-tab>
</mat-tab-group>

Script

onTabChange(event: MatTabChangeEvent) {
  const tabName = event.tab.textLabel;
  // ...
}

Basically, this uses the other way to add a (title) text label to the tab, using <ng-template>, which seems to take precedence over the label attribute.

This latter attribute can therefore be used to store the "programmatic" name of the tab (as opposed to its public text) and is easily retrieved on script side.


Use aria-labelledby attribute to identify tab without resorting to human-readable text labels.

<mat-tab aria-labelledby="tab-x">
    <span *matTabLabel id="tab-x" i18n>Tab X</span>
</mat-tab>

In the code:

onTabChange(event: MatTabChangeEvent) {
    const tabId = event.tab.ariaLabelledby;
    if (tabId === 'tab-x') { ... }
}