首页 > 解决方案 > 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);

标签: angularangular-materialangular-material-table

解决方案


您可能需要调用 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
    }
  );
}

推荐阅读