Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change a tab without causing selectedIndexChange

I need to change a tab programmatically without firing the selectedIndexChange event.

I made a stackBlitz example here. The related code is the following:

<mat-tab-group [selectedIndex]="tabIndex" (selectedIndexChange)="informChange($event)">
  <mat-tab label="Tab 1"></mat-tab>
  <mat-tab label="Tab 2"></mat-tab>
  <mat-tab label="Tab 3"></mat-tab>
  <mat-tab label="Tab 4"></mat-tab>
  <mat-tab label="Tab 5"></mat-tab>
</mat-tab-group>
<br>
<button mat-raised-button color="primary" (click)="goToTab3()">Change Tab</button>

With the respective class

export class AppComponent {
  tabIndex = 0;

  goToTab3() {
    this.tabIndex = (this.tabIndex + 1) % 5;
  }

  informChange(tabIndex:number) {
    console.log(tabIndex);
  }
}

What I want is that the tab will change on every button click but the event handler that is attached to the selectedIndexChange event should not get executed.

So I need to distinguish between a tab click which in that case I do want the selectedIndexChange to fire, and between a change made by code (the button in this example but could be a change from another part such as a store/redux change) which in that case I dont want the selectedIndexChange to fire but only change the selected tab.

like image 840
Udi Mazor Avatar asked Sep 03 '25 03:09

Udi Mazor


1 Answers

You could use another event, focusChange

<mat-tab-group [selectedIndex]="tabIndex" (focusChange)="informChange($event.index)">

Remember that you get a MatTabChangeEvent instead of an index in that case, so you need to use $event.index in order to get the particular index that you are after.

like image 136
Patrick Avatar answered Sep 06 '25 21:09

Patrick