当用户被编辑时,我正在尝试更新我的数据表。
目前,数据源已更新,但在前面部分看不到更改。我的意思是,我的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);