Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 300
1Z10 Avatar asked Jun 14 '18 09:06

1Z10


2 Answers

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

like image 143
bugs Avatar answered Oct 07 '22 12:10

bugs


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

Selected tab will trigger out the tabChange Event and get the active tab.

And in the .ts file:

onChange(event: MatTabChangeEvent) {
    const tab = event.tab.textLabel;
    console.log(tab);
    if(tab===" Tab 1")
     {
       console.log("function want to implement");
      }
  }
like image 31
Hans Avatar answered Oct 07 '22 11:10

Hans