7

I want to change activated mat-tab in typescript file. Here Programmatically select md-tab in Angular 2 material I found the closest solution but for md-tab not mat-tab.I tried this but didn't work.Here what I tried

HTML

  <button class="btn btn-primary" (click)="changeTab()">Click me!</button>

    <mat-tab-group [selectedIndex]="selectedTab">
        <mat-tab label="Preview"> 
    </mat-tab>
        <mat-tab label="Tuning">
        <car-tuning></car-tuning>
        </mat-tab>
        <mat-tab label="Payment"></mat-tab> 
      </mat-tab-group> 

.TS File

 changeTab() {
     this.selectedTab =1;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Timuçin Çiçek
  • 1,516
  • 3
  • 14
  • 39
  • There's [an example on the site showing how to programmatically set the selected tab](https://material.angular.io/components/tabs/examples) (fourth one down). – Heretic Monkey Sep 12 '19 at 12:37

2 Answers2

7

You can add two way binding like this [(selectedIndex)]="selectedTab" and should give you result.

<button class="btn btn-primary" (click)="changeTab()">Click me!</button>

<mat-tab-group [(selectedIndex)]="selectedTab"> //<--- changes
   <mat-tab label="Preview"> 
   </mat-tab>
   <mat-tab label="Tuning">
     <car-tuning></car-tuning>
   </mat-tab>
    <mat-tab label="Payment"></mat-tab> 
</mat-tab-group> 

In ts:

changeTab() {
   this.selectedTab = 1 //<------- your tab value
}
Tushar
  • 1,948
  • 1
  • 13
  • 32
Nenad Radak
  • 3,550
  • 2
  • 27
  • 36
  • the Bannanabox binding here does the trick. In the Api Examples its not clearly highlighted https://material.angular.io/components/tabs/examples#tab-group-dynamic – norca Mar 09 '23 at 08:49
2

yes you can change like this.

<mat-tab-group [(selectedIndex)]="selectedIndex">
    <mat-tab>

    </mat-tab>
    <mat-tab>

    </mat-tab>
    <mat-tab>

    </mat-tab>
</mat-tab-group>

In ts use:

selectedIndex: number;

in your function

this.selectedIndex = whateverIndexYouWant;

here is how I change activated index from ts.

this.data.currentMessage.subscribe(message => {
  switch (message) {
    case 'blabla':
      this.selectedIndex = 0;
      break;
    case 'blablablabla':
      this.selectedIndex = 1;
      break;
    case 'blablablablablabla':
      this.selectedIndex = 2;
      break;
  }
});
GreedyAi
  • 2,709
  • 4
  • 29
  • 55