首页 > 解决方案 > 将附加数据附加到角度组件

问题描述

我有几个动态生成的MatTable组件(由 *ngFor):

<div *ngFor="....">
  <table mat-table [attr.data-table-id]="someId" >
    ....
  </table>
  .....
</div>

现在,在组件的类文件中,我想找到一个特定的 MatTable 参考。我在组件类中定义了一个属性:

@ViewChildren(MatTable) tables: QueryList<MatTable>;

现在,我参考了所有的 MatTables。但我想找到一个特定的 MatTable,例如具有特定属性的 MatTable(例如 data-table-id = 12)。如何访问每个 MatTable 的对应 DomElement?如果我可以获得对组件的相应 DomElement 的引用,我可以读取该元素的属性并找到我想要的组件(MatTable)。

标签: angularangular-material

解决方案


您可以使用基本的 HTML id 标记,并通过以下方式访问它:

  <table mat-table id="myId" [attr.data-table-id]="someId" >
    ....
  </table>

在组件中:

@ViewChildren(MatTable, {read: ElementRef}) public tables: QueryList<ElementRef>;

let theTableIWant: ElementRef = this.tables.find((el: ElementRef) => el.nativeElement.id === myId);

推荐阅读