问题描述
我显示了几个带有循环的选项卡ngFor使用Angular Material选项卡.这可以正常工作,但是现在我想在初始化时打开第二个选项卡,而不是第一个选项卡.因此,我在mat-tab-group组中添加了selectedIndex属性,但是它不起作用,并且仍然在第一个选项卡上继续打开.
I display several tabs with a loop ngFor using Angular Material tabs.This works properly however now I would like to open the second tab when initialised and not the first tab.Therefore, I add the property selectedIndex in the mat-tab-group but it doesn't work and still continues to open on the first tab.
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>
使用服务从ngOnInit的服务器中获取变量"tabs" ,如下所示:
The variable "tabs" is fetched with a service from the server in ngOnInit like this:
组件
this.api.getDataset(this.route.snapshot.params["experimentid"]).subscribe(
res => {
this.tabs = res;
},
err => {
console.log(err);
}
);
我认为它来自这里,因为如果我手动设置选项卡而不请求服务器,它将起作用.像这样:
I think it comes from here because if I set the tabs manually without requesting to the server it works. Like this:
this.tabs = [{name: "X2", values: "52"}, {name: "Z2", values: "52"}, {name: "R2", values: "52"}]
推荐答案
您可以在服务数据可用后设置selectedIndex
.您需要进行以下更改:
You can set the selectedIndex
after your service data is available. You need to do below changes:
-
通过声明以下属性来获取对组件(其模板包含
mat-tab-group
的组件)中的MatTabGroup
实例的引用:
Get hold of a reference to
MatTabGroup
instance in your component (the component whose template containsmat-tab-group
) by declaring below attribute:
@ViewChild(MatTabGroup) tabGroup: MatTabGroup;
然后在更新tabs
.subscribe(
res => {
this.tabs = res;
this.tabGroup.selectedIndex = 1;
},
总体而言,您的组件可能看起来如下所示:
Overall, you component may look somewhat like below:
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);
}
);
}
}
这篇关于Mat-tab材质angular6 selectedIndex不适用于* ngFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!