Angular Material Table - 如何更新现有 table 的列 header?

Angular Material Table - How to update column header of an existing table?

我正在使用 Angular 7,我有一个带有 Angular Material Table 的简单组件。通过某些事件,比如单击鼠标,我希望能够更新现有 table.

的数据和 header

之前:

(目标)之后:

目前,我正在获取要更新的数据。但是,我无法获取要更新的列的 header 文本,除非我做了一个相当矫揉造作的 window 超时调用。

这很难描述,所以 stackblitz repo 应该有所帮助。在我链接到那里的 'table-dynamic-columns.example.ts' 文件中,我在 'changeColumnHeader' 按钮单击处理程序上尝试了两种不同的策略。看来,为了让我的新列 header 标题显示出来,我需要先清除 table 的显示列,然后在超时时将它们正确设置回来。也许它不起作用,因为 属性 名称保持不变(即 'id'),只有标题发生变化。

有谁知道正确更新的更好方法吗?

Maybe it's not working because the property name stays the same (i.e. 'id') and only the title changes.

这就是它不更新的原因,如本 comment

所述

在同一评论中,有一个建议的解决方案,您可以使用(添加 trackBy 功能)。

为此,请在您的模板中包含 trackBy

<ng-container [matColumnDef]="config.property" *ngFor="let config of configs; trackBy: trackByIndex">
<th mat-header-cell *matHeaderCellDef> {{config.name}} </th>
<td mat-cell *matCellDef="let element"> {{element[config.property]}} </td>

在您的组件 ts 文件中包含函数 trackByIndex

trackByIndex(i) { return i; }

分叉了您提供的 stackblitz,它正在运行 here