fresher
fresher

Reputation: 399

how to trigger function on active tab in mat-tab

using angular 6 and I have 2 components I am using mat-tab and I have 3 tabs Each tab calls a component

<mat-tab label="one">
<score-football ></ score-football >
</mat-tab>

<mat-tab label="second">
<score-hockey ></ score-hockey >
</mat-tab>

<mat-tab label="third">
<score-others ></ score-others>
</mat-tab>

How to execute or trigger a function within component, every time tab gets into focus For example, whenever a “second” tab active, I want to trigger a function

getFreshScore(){
alert(‘going to get fresh score from DB’);
}  

so each time my score get refresh

Upvotes: 1

Views: 2083

Answers (1)

Stavm
Stavm

Reputation: 8131

MatTabGroup emits an event called selectedIndexChange - use it.

HTML:

<mat-tab-group (selectedIndexChange)="getFreshScore($event)">
  <mat-tab label="First"> Content 1 </mat-tab>
  <mat-tab label="Second"> Content 2 </mat-tab>
  <mat-tab label="Third"> Content 3 </mat-tab>
</mat-tab-group>

Component:

getFreshScore(index: number) {
    alert('going to get fresh score from DB ' + index);
  }

DEMO

Upvotes: 1

Related Questions