如何在 Angular Material2 中获取活动选项卡 [英] How to get the active tab In Angular Material2
问题描述
我想知道哪个 tab 处于活动状态.我尝试使用 @ViewChild
装饰器并以这种方式访问元素属性,但它返回 null
.
I want to get which tab is active. I tried to use a @ViewChild
decorator and accessing the element properties that way, but it returns null
.
组件:
import {Component, OnInit, ViewChild} from '@angular/core';
@Component({
selector: 'material-app',
template: `
<md-tab-group #tabGroup>
<md-tab label="Tab 1">Content 1</md-tab>
<md-tab label="Tab 2">Content 2</md-tab>
</md-tab-group>
`
})
export class AppComponent implements OnInit {
@ViewChild('tabGroup') tabGroup;
constructor() {
}
ngOnInit() {
console.log(this.tabGroup); // MdTabGroup Object
console.log(this.tabGroup.selectedIndex); // null
}
}
推荐答案
好吧,我不确定我是否理解你的问题,因为默认情况下索引总是从零开始计数除非你手动设置[selectedIndex] 属性
.
Well, I'm not sure if I understood well your question because, by default the index always starts counting from zero unless you set manually the [selectedIndex] property
.
无论如何,如果您真的想查看在初始化中选择了哪个选项卡,您可以实现AfterViewInit
接口并执行以下操作:
Anyway, if you really want to see which tab is selected on initialization you could implement the AfterViewInit
interface and do the following:
export class AppComponent implements AfterViewInit, OnInit {
...
ngAfterViewInit() {
console.log('afterViewInit => ', this.tabGroup.selectedIndex);
}
}
另一方面,如果您想根据更改(更有意义)检查选择了哪个选项卡,请执行以下操作:
On other hand, if you want to check which tab is selected based on changes (what makes more sense), here you go:
HTML:
<mat-tab-group #tabGroup (selectedTabChange)="tabChanged($event)">
<mat-tab label="Tab 1">Content 1</mat-tab>
<mat-tab label="Tab 2">Content 2</mat-tab>
</mat-tab-group>
组件:
tabChanged(tabChangeEvent: MatTabChangeEvent): void {
console.log('tabChangeEvent => ', tabChangeEvent);
console.log('index => ', tabChangeEvent.index);
}
这篇关于如何在 Angular Material2 中获取活动选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!