How can I select a specific tab when an event occurs?
I tried with [selectedIndex]="selectedTab"
changing the selectedTab
to the tab index needed but it doesn't seems to work after the tabs are loaded.
The solution 🕶 First, we need to add a click listener on the mat-tab-group and disable all tabs because if tabs are not disabled then the user will be able to navigate on them and we want to navigate on tabs conditionally not manually.
You can use selectedIndex property to set the default tab on the tab group. Setting selectedIndex property as 0 sets the first tab and setting it as 1 sets the second tab.
If you want to align the tab labels in the center or towards the end of the container, you can do so using the [mat-align-tabs] attribute.
Material tabs (with matTabContent ) are rendering multiple instances of the tab body inside the same tab when switching away and back too fast.
UPDATE (using newest angular+material)
there are multiple ways..
<button mat-raised-button (click)="demo1BtnClick()">Tab Demo 1!</button> <mat-tab-group [(selectedIndex)]="demo1TabIndex"> <mat-tab label="Tab 1">Content 1</mat-tab> <mat-tab label="Tab 2">Content 2</mat-tab> <mat-tab label="Tab 3">Content 3</mat-tab> </mat-tab-group>
public demo1TabIndex = 1; public demo1BtnClick() { const tabCount = 3; this.demo1TabIndex = (this.demo1TabIndex + 1) % tabCount; }
<button mat-raised-button (click)="demo2BtnClick(demo2tab)">Tab Demo 2!</button> <mat-tab-group #demo2tab> <mat-tab label="Tab 1">Content 1</mat-tab> <mat-tab label="Tab 2">Content 2</mat-tab> </mat-tab-group>
public demo2BtnClick(tabGroup: MatTabGroup) { if (!tabGroup || !(tabGroup instanceof MatTabGroup)) return; const tabCount = tabGroup._tabs.length; tabGroup.selectedIndex = (tabGroup.selectedIndex + 1) % tabCount; }
<button mat-raised-button (click)="demo3BtnClick()">Tab Demo 3!</button> <mat-tab-group #demo3Tab> <mat-tab label="Tab 1">Content 1</mat-tab> <mat-tab label="Tab 2">Content 2</mat-tab> </mat-tab-group>
@ViewChild("demo3Tab", { static: false }) demo3Tab: MatTabGroup; public demo3BtnClick() { const tabGroup = this.demo3Tab; if (!tabGroup || !(tabGroup instanceof MatTabGroup)) return; const tabCount = tabGroup._tabs.length; tabGroup.selectedIndex = (tabGroup.selectedIndex + 1) % tabCount; }
live-demo: https://stackblitz.com/edit/angular-selecting-mattab?file=src%2Fapp%2Fapp.component.ts
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