要获取mat-tab内部的组件,需要使用@ViewChild从父组件获取子组件的引用,然后再通过子组件引用获取内部组件。 示例代码如下:
HTML:
在 Tab1Component 中使用 @ViewChild:
export class Tab1Component implements OnInit { @ViewChild('myTabs') tabs: MatTabGroup;
ngOnInit() {
const selectedTab = this.tabs.selectedIndex;
const tabLabel = this.tabs._tabs[selectedTab].textLabel.nativeElement.innerText;
console.log(Selected Tab Label: ${tabLabel}
);
}
}
在上面的代码中,我们将 tabs 组件引用设置为 @ViewChild('myTabs'),然后使用该引用获取所选标签的文本标签。通常在 ngOnInit 钩子中获取这些属性。