Angular Material mat-tab子组件如何获取父级mat-tab的label属性值
实现方案
方案1:直接属性传值(最推荐,耦合度最低)
无需修改组件逻辑结构,通过Angular输入属性绑定传值即可,是业务开发中最常用的实现方式:
- 首先给
ExampleComponent的label属性加上@Input()装饰器:
import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: 'exampleComponent', templateUrl: './exampleComponent.html' }) export class ExampleComponent implements OnInit { @Input() label: string; ngOnInit(): void { // 此处可直接拿到父级tab传过来的label值 console.log('当前tab的label:', this.label); } }
- 在父组件模板中给每个
exampleComponent绑定对应的label值:
<mat-tab-group> <mat-tab label="dog"> <exampleComponent [label]="'dog'"></exampleComponent> </mat-tab> <mat-tab label="cat"> <exampleComponent [label]="'cat'"></exampleComponent> </mat-tab> <mat-tab label="bunny"> <exampleComponent [label]="'bunny'"></exampleComponent> </mat-tab> </mat-tab-group>
如果要避免重复写字符串,可以把tab配置抽成数组用*ngFor渲染,代码会更简洁:
- 父组件ts中定义tab配置:
tabs = [ {label: 'dog'}, {label: 'cat'}, {label: 'bunny'} ]
- 父组件模板简化为:
<mat-tab-group> <mat-tab *ngFor="let tab of tabs" [label]="tab.label"> <exampleComponent [label]="tab.label"></exampleComponent> </mat-tab> </mat-tab-group>
方案2:子组件注入父MatTab实例(无需手动传值)
如果不想在父模板中手动绑定值,可以通过Angular依赖注入直接获取父级MatTab实例,读取它的原生label属性:
import { Component, OnInit, Optional, Host } from '@angular/core'; import { MatTab } from '@angular/material/tabs'; @Component({ selector: 'exampleComponent', templateUrl: './exampleComponent.html' }) export class ExampleComponent implements OnInit { label: string; constructor(@Optional() @Host() private parentTab: MatTab) {} ngOnInit(): void { if (this.parentTab) { this.label = this.parentTab.label; console.log('当前tab的label:', this.label); } } }
其中@Optional装饰器用来避免组件不在mat-tab内部使用时报错,@Host装饰器限定只从当前组件的宿主层级往上查找父级依赖。
两种方案按需选择即可,优先选方案1,逻辑更透明,组件复用性更强,不依赖Angular Material的内部实现。
内容的提问来源于stack exchange,提问作者Enrique Metner
相关产品推荐
相关产品推荐

