matTable:UI 更改数据源行后未更新

matTable: UI not updating after altering a datasource row

我正在尝试在用户被编辑后更新我的数据表。

此时,数据源已更新,但更改在前面部分不可见。我的意思是,我的 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 上添加了一个参考,例如:<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

If the table's data source is a DataSource or Observable, this will be invoked automatically each time the provided Observable stream emits a new data array. Otherwise if your data is an array, this function will need to be called to render any changes.

/**
* 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
    }
  );
}