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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With