angular - matTable:更改数据源行后 UI 未更新
问题描述
当用户被编辑时,我正在尝试更新我的数据表。
目前,数据源已更新,但在前面部分看不到更改。我的意思是,我的console.log(this.dataSource)
表演数据很好。但在网页上并非如此。
这是我获取数据源 (ngOnInit) 的方法:
this.users.users().subscribe(data => {
this.dataSource.data = data;
});
这是我的update
功能:
/**
* Update an user
* @param user The user to update
*/
update(user: User) {
// users = user's services
this.users.edit(user)
.subscribe(
userEdited => {
const userIndex = this.dataSource.data.findIndex(usr => usr.id === user.id);
console.log('Before change :', this.dataSource.data[userIndex], userIndex);
this.dataSource.data[userIndex] = userEdited;
console.log('After change :', this.dataSource.data[userIndex], this.dataSource.data);
}
);
}
解决方案
我需要调用renderRows()
函数。
所以我在我的桌子上添加了一个参考,比如:<table mat-table #table [dataSource]="dataSource">
然后我声明一个@ViewChild
属性@ViewChild('table', { static: true }) table: MatTable<any>;
然后 :
const userIndex = this.dataSource.data.findIndex(usr => usr.id === user.id);
console.log('Before change :', this.dataSource.data[userIndex], userIndex);
this.dataSource.data[userIndex] = userEdited;
this.table.renderRows(); // <--- Add this line
console.log('After change :', this.dataSource.data[userIndex], this.dataSource.data);
解决方案
您可能需要调用 renderRows() 函数,请参阅https://material.angular.io/components/table/api
如果表的数据源是 DataSource 或 Observable,则每次提供的 Observable 流发出新的数据数组时都会自动调用。否则,如果您的数据是一个数组,则需要调用此函数来呈现任何更改。
/**
* Update an user
* @param user The user to update
*/
update(user: User) {
this.users.edit(user)
.subscribe(
userEdited => {
const userIndex = this.dataSource.data.findIndex(usr => usr.id === user.id);
this.dataSource.data[userIndex] = userEdited;
this.table.renderRows(); // <--- Add this line
}
);
}
推荐阅读
- ios - 如何在 kizoa 应用程序中制作图像/视频过渡动画
- c# - 无法从 tcp 服务器读取数据
- ionic4 - Ionic 4 Capacitor 选择适用于 Android 和 IOS 的文件
- angular - Angular 材质深色主题
- ionic-framework - 位置不可用电容器离子
- arrays - 运行包含大量原始数据的查询
- firebase - Firebase 云消息传递 click_action 不起作用
- python - 哪里 col 等于 value 复制到单独的 col - Pandas
- c# - 滑动以验证 puppteer-sharp 失败
- sap-cloud-sdk - 模拟 Https 目标以连接到 OAuth2 身份验证后面的系统