Programmatically select md-tab in Angular 2 materi

2019-02-11 12:13发布

how can I select a specific tab when an event occur?

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...

3条回答
Viruses.
2楼-- · 2019-02-11 12:44

I had the same issue and I tried the above answers but they are not helping. Here is my solution:

In my typescript code, first, declare a variable:

selected = new FormControl(0); // define a FormControl with value 0. Value means index.

then, in the function:

changeTab() {
    this.selected.setValue(this.selected.value+1);
 } //

in the html,

 <mat-tab-group [selectedIndex]="selected.value" (selectedIndexChange)="selected.setValue($event)">
            <mat-tab label="label0">0</mat-tab>
            <mat-tab label="label1">1</mat-tab>
            <mat-tab label="label2">2</mat-tab>
            <mat-tab label="label3">3</mat-tab>
            <mat-tab label="label4">4</mat-tab>
            <mat-tab label="label5">5</mat-tab>
</mat-tab-group>

<button (click)="changeTab()">ChangeTab</button>
查看更多
冷血范
3楼-- · 2019-02-11 12:59

In case it helps anyone, it is also possible to set selectedIndex on the MatTabGroup in your component.

If your HTML has: <mat-tab-group #tabs>, you can get a reference to it in the component using @ViewChild('tabs') tabGroup: MatTabGroup;.

Then you can do this.tabGroup.selectedIndex = newIndex; in the OnInit function, or elsewhere.

查看更多
戒情不戒烟
4楼-- · 2019-02-11 13:02

Should work, maybe anywhere else a problem? Any error message?

<button md-raised-button (click)="changeTab()">Click me!</button>

<md-tab-group [selectedIndex]="selectedTab">
  <md-tab label="Tab 1">Content 1</md-tab>
  <md-tab label="Tab 2">Content 2</md-tab>
</md-tab-group>
changeTab() {
  this.selectedTab += 1;
  if (this.selectedTab >= 2) this.selectedTab = 0;
}

live-demo: http://plnkr.co/edit/k2cw7Jw5YEstrY3OWbdq?p=preview

查看更多
登录 后发表回答