我使用 Angular Material 选项卡显示几个带有循环 ngFor 的选项卡。 这工作正常但是现在我想在初始化时打开第二个选项卡而不是第一个选项卡。 因此,我在 mat-tab-group 中添加了属性 selectedIndex,但它不起作用并且仍然继续在第一个选项卡上打开。
HTML
<mat-tab-group class="col-10 offset-1" (selectedTabChange)="onTabChanged($event)" [selectedIndex]="1">
<mat-tab label={{tab.name}} *ngFor="let tab of tabs; let index = index">
<div>
Values: {{tab.values}}
</div>
</mat-tab>
</mat-tab-group>
变量 “tabs” 在 ngOnInit 中通过服务从服务器获取,如下所示:
组件
this.api.getDataset(this.route.snapshot.params["experimentid"]).subscribe(
res => {
this.tabs = res;
},
err => {
console.log(err);
}
);
我认为它来自这里,因为如果我在不请求服务器的情况下手动设置选项卡,它就可以工作。像这样:
this.tabs = [{name: "X2", values: "52"}, {name: "Z2", values: "52"}, {name: "R2", values: "52"}]
最佳答案
您可以在服务数据可用后设置selectedIndex
。您需要进行以下更改:
通过声明以下属性,在您的组件(其模板包含
mat-tab-group
的组件)中获取对MatTabGroup
实例的引用:@ViewChild(MatTabGroup) tabGroup: MatTabGroup;
然后在
subscribe
方法调用中设置 selectedIndex,同时更新tabs
的新值.subscribe( res => { this.tabs = res; this.tabGroup.selectedIndex = 1; },
总的来说,您的组件可能看起来像下面这样:
import {Component, OnInit, ViewChild } from '@angular/core';
import { MatTabGroup } from '@angular/material';
@Component({
selector: 'tab-group-basic-example',
templateUrl: 'tab-group-basic-example.html',
styleUrls: ['tab-group-basic-example.css'],
})
export class TabGroupBasicExample implements OnInit {
@ViewChild(MatTabGroup) tabGroup: MatTabGroup;
tabs = [];
ngOnInit() {
this.api.getDataset(experimentId).subscribe(
res => {
this.tabs = res;
this.tabGroup.selectedIndex = 1;
},
err => {
console.log(err);
}
);
}
}
关于angular - Mat-tab Material angular6 selectedIndex 不适用于 *ngFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51342582/