angularangular-materialangular5angular-material-5

Angular Material 5: how to call a function when a tab is selected (clicked)?


I have the following html code

<mat-tab label="Regular" (selectChange)="tabClick()"
                 (click)="tabClick()">
   <h1>Some more tab content</h1>
</mat-tab>

and this is the function,

tabClick(){
    console.log('Tab clicked...');
}

but it doesn't seems to be called, why? No one of the above events are fired?


Solution

  • The selectedTabChanged event has to be attached to the <mat-tab-group> element

    <mat-tab-group (selectedTabChange)="tabClick($event)">
      <mat-tab label="Tab 1">Content 1</mat-tab>
      <mat-tab label="Tab 2">Content 2</mat-tab>
    </mat-tab-group>
    

    tabClick(tab) {
      console.log(tab);
    }
    

    Demo