<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.field">
<th mat-header-cell *matHeaderCellDef> {{column.header}} </th>
<td mat-cell *matCellDef="let element"> {{element[column.field]}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<button (click)="test()">Button to update data and header</button>
stackblitz链接在此处链接到相同的问题:
https://stackblitz.com/edit/vnd2caeh?file = src%2fexample%2fexample%2ftable-basic-example.tspample.ts
当我单击“按钮更新数据和标头”的按钮时,您可以看到,我更改标题和内容的基础数据。它没有更新数据的问题,但由于某种原因,表标头未更新。
我尝试手动触发变更检测并重新渲染桌子,但没有任何效果。 不确定我缺少什么,但是您的帮助将不胜感激。
在此GitHub问题中提到了您的方案:表与动态列 - 页脚 /标头在上下文更改#13030
.之后不会更新。
您需要触发removeHeaderRowDef
import { Component, ViewChild } from '@angular/core';
import { MatHeaderRowDef, MatTable, MatTableDataSource, MatTableModule, } from '@angular/material/table';
@ViewChild(MatTable) table: MatTable<any>;
@ViewChild(MatHeaderRowDef, {static: true}) headerDef: MatHeaderRowDef;
test() {
...
this.table.removeHeaderRowDef(this.headerDef);
}