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

4

17

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?

Asphodel answered 14/6, 2018 at 9:35 Comment(0)
I
38

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

Isoline answered 14/6, 2018 at 9:38 Comment(4)
ok, then how to detect which tab was selected, e.g. passing the tab label to tabClick('selectedLabel') ?Asphodel
You have to pass the $event object, see updated answerIsoline
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).Pythagoreanism
still, both tabs are triggering the method. How can we do it that only one of the tab will trigger the method?Capitulum
P
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>
Pelops answered 14/6, 2018 at 9:37 Comment(1)
@Isoline Yup, I forgot to change Element name , Answer UpdatedPelops
D
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");
      }
  }
Disapprobation answered 29/5, 2020 at 5:43 Comment(1)
this is more type safe and should be answerWandy
K
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)
    }
Krebs answered 1/6, 2022 at 10:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.