1Z10
1Z10

Reputation: 3301

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?

Upvotes: 17

Views: 66423

Answers (4)

Gaurav Jaiswal
Gaurav Jaiswal

Reputation: 1

SelectTab is used to call click-on tab data.

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

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

Upvotes: 0

Hans
Hans

Reputation: 318

<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");
      }
  }

Upvotes: 4

bugs
bugs

Reputation: 15313

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

Upvotes: 38

Pardeep Jain
Pardeep Jain

Reputation: 86730

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>

Upvotes: 9

Related Questions