角度材质2 - 获取第一个标签的标签

时间:2017-10-23 06:32:38

标签: angular angular-material angular-material2

我需要获取用户点击的任何标签的值。这是我到目前为止所做的:

<mat-tab-group (selectedTabChange)="getLabel($event)" #tabGroup>
    <mat-tab label="{{ thing.name }}" *ngFor="let thing of things | async" #tab>
        ....
    </mat-tab>
</mat-tab-group>

TS - 数据库提取:

thingsCollection: AngularFirestoreCollection<Intf>;
things: Observable<Intf[]>;

ngOnInit() {
    this.thingsCollection = this.afs.collection(placeToSearch2);
    this.things = this.thingsCollection.valueChanges();
}

问题是我还需要label首次加载的选项卡的mat-tab-group属性的值。 (selectedTabChange)仅在用户在标签上手动点击时触发。这很好,但没有给我第一个标签的标签。

有一个类似的问题here有一个很好的答案,但当我更清楚地问他我的特定问题时,评论者似乎对我很生气。他提供的答案接近我的要求:

ngAfterViewInit() {
    console.log('afterViewInit => ', this.tabGroup.selectedIndex); // Close, but no cigar
  }

上面的解决方案只给我索引(几乎总是0),而不是label。我怎样才能获得标签? Angular Tab reference显示有一个textLabel属性。我认为这可能是答案,但它使用我不熟悉的@Input。有人可以帮我使用吗?

2 个答案:

答案 0 :(得分:3)

您可以使用以下方式获取它:

this.tabGroup._tabs.first.textLabel

release notes

答案 1 :(得分:1)

你应该尽可能地坚持使用公共api,而不是依赖于核心实现,因为将来如果他们改变你的应用程序将破坏的内部。 您可以将组件更改为 添加

  @ViewChildren(MatTab) tabs: QueryList<MatTab>;

这将查询所有标签并创建查询列表。

然后在初始化时,当您的数据到达时,您应该检查第一个选项卡。 所以在您的组件中,您可以这样做,

  ngOnInit() {
      this.thingsCollection = this.afs.collection(placeToSearch2);
      this.things = this.thingsCollection.valueChanges();
      this.things.finally(() => {
          setTimeout(() => { this.checkSelection(); });
      });
  }

  checkSelection() {
    let tab = this.tabs.first;
    console.log('selected tab', tab);
  }

这将查询列表,并为您提供第一个标签。