Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I switch from one Angular 2 material tabs to another in typescript?

I have two tabs and two buttons

<md-tab-group>
<md-tab label="Tab 1">Content 1</md-tab>
  <md-tab label="Tab 2">Content 2</md-tab>
</md-tab-group>
<button md-button (click)="showTab1()">Show Tab 1</button>
 <button md-button (click)="showTab2()">Show Tab 2</button>

I need the function showTab1() to switch to tab 1 if I am on Tab 1 and showTab2() to be executed if the button is clicked. Can anyone help?

like image 539
IsaacK Avatar asked Feb 13 '17 11:02

IsaacK


1 Answers

You can use the [selectedIndex] @Input for mat-tab-group:

Component:

selectedIndex = 0;

selectTab(index: number): void {
  this.selectedIndex = index;
}

Template:

<mat-tab-group [selectedIndex]="selectedIndex">
  <mat-tab label="Tab 1">Content 1</mat-tab>
  <mat-tab label="Tab 2">Content 2</mat-tab>
</mat-tab-group>

<button mat-button (click)="selectTab(0)">Show Tab 1</button>
<button mat-button (click)="selectTab(1)">Show Tab 2</button>

STACKBLITZ DEMO

... or you can create a reference to the mat-tab-group and manipulate it directly in template:

<mat-tab-group #tabGroup>
  <mat-tab label="Tab 1">Content 1</mat-tab>
  <mat-tab label="Tab 2">Content 2</mat-tab>
</mat-tab-group>

<button mat-button (click)="tabGroup.selectedIndex = 0">Show Tab 1</button>
<button mat-button (click)="tabGroup.selectedIndex = 1">Show Tab 2</button>

STACKBLITZ DEMO

like image 139
developer033 Avatar answered Sep 24 '22 19:09

developer033