15

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?

1Z10
  • 2,801
  • 7
  • 33
  • 82

4 Answers4

37

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

bugs
  • 14,631
  • 5
  • 48
  • 52
  • ok, then how to detect which tab was selected, e.g. passing the tab label to tabClick('selectedLabel') ? – 1Z10 Jun 14 '18 at 09:39
  • 2
    You have to pass the `$event` object, see updated answer – bugs Jun 14 '18 at 09:41
  • 1
    In my eyes, the answer is almost, but not entirely correct. The `click` event usually is triggered before the tab is changed. `selectChange` is triggered after the tab has changed. You can use it to prevent the tab change, nor can you use it to clear the resources of components while they are visible. (Granted, the latter is an unusual use-case, but it's the use-case I'm currently fighting with). – Stephan Rauh Dec 04 '18 at 12:41
  • still, both tabs are triggering the method. How can we do it that only one of the tab will trigger the method? – Gel Apr 21 '20 at 17:22
9

An event should be selectedTabChange to the mat-tab-group

<mat-tab-group (selectedTabChange)="tabClick()">
    <mat-tab label="Regular">
       <h1>Some more tab content</h1>
    </mat-tab>
</mat-tab-group>
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
4
<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");
      }
  }
Gaël J
  • 11,274
  • 4
  • 17
  • 32
Hans
  • 308
  • 7
  • 20
0

SelectTab is used to call click-on tab data.

 <tab (selectTab) = "onChange($event)" >
        <div>
            any data
        </div>
    </tab >
    

    onChange(data:any){
    console.log(data)
    }