Programmatically select mat-tab in Angular 2 material using mat-tab-group

UPDATE (using newest angular+material)

there are multiple ways..

  1. possible solution, using two-way databinding
<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;
}
  1. possible solution, using template-variable and pass through our click-function
<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;
}
  1. possible solution, using @ViewChild
<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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)