角度材料表 - 如何更新现有表的列标题? [英] Angular Material Table - How to update column header of an existing table?

查看:21
本文介绍了角度材料表 - 如何更新现有表的列标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Angular 7,我有一个带有

之后(目标):

目前,我正在获取数据以进行正常更新.但是,我无法更新列的标题文本,除非我做了一个相当糟糕的窗口超时调用.

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

有没有人知道让这个正确更新的更好方法?

解决方案

也许它不起作用,因为属性名称保持不变(即id")并且只有标题发生了变化.

这就是它不更新的原因,正如在此评论

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

为此,请在模板中包含 trackBy:

<th mat-h​​eader-cell *matHeaderCellDef>{{config.name}} </th><td mat-cell *matCellDef="let element">{{element[config.property]}} </td>

在组件 ts 文件中包含函数 trackByIndex:

trackByIndex(i) { return i;}

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

I'm using Angular 7 and I have a simple component with an Angular Material Table. Through some event, say a mouse click, I want to be able to update both the data and the header of that existing table.

Before:

After (goal):

Currently, I'm getting the data to update fine. However, I can't get the header text of the columns to update unless, that is, I do a fairly hokey window timeout call.

This is hard to describe, so a stackblitz repo should help. The in 'table-dynamic-columns.example.ts' file I've linked there, I have two different strategies that I try on the 'changeColumnHeader' button click handler. It appears that in order to get my new column header title to show up, I need to first clear out the displayed columns of the table, and then set them back properly in a timeout. Maybe it's not working because the property name stays the same (i.e. 'id') and only the title changes.

Does anyone know a better way to get this to update correctly?

解决方案

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

Thats the reason for it not updating, as explained on this comment

On the same comment, there is a proposed solution that you may use (add a trackBy function).

For doing this, include trackBy on your template:

<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>

Include function trackByIndex on your component ts file:

trackByIndex(i) { return i; }

Forked the stackblitz you provided and it is working here

这篇关于角度材料表 - 如何更新现有表的列标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆