首页 > 解决方案 > Angular Material Dialog:如何在 afterClosed 更改后更新表格行中的数据?

问题描述

关闭表中的模式对话框后不更新行。行中this.usersData已更新,但表中未更新。我如何更新行?

usersData: MatTableDataSource<any>;

listUsers() {
    this.usersService.usersList(limit, page, param)
      .subscribe((res) => {
          this.usersData = new MatTableDataSource(res.rows);
        },
        (err) => {
          console.log('listUsers_err', err);
        }
      );
}

editUser(id, i) {
    const dialogConfig = {
      disableClose: true,
      autoFocus: false,
      data: {
        userId: id
      }
    };

    const dialogRef = this.dialog.open(UserEditComponent, dialogConfig);

    dialogRef.afterClosed().subscribe(result => {
      this.usersData.data[i] = result;    // <--- not updated in table aftrer close modal
    });
  }

"@angular/material": "^11.0.3",

标签: angularangular-material

解决方案


如果提供了数据数组,则必须在添加、删除或移动数组的对象时通知表。这可以通过调用renderRows()将呈现自上次表呈现以来的差异的函数来完成。如果数据数组引用发生变化,表会自动触发对行的更新,表api...

export class Component {
  @ViewChild(MatTable) table: MatTable<any>;

  ...
  editUser(id, i) {
    ...
    dialogRef.afterClosed().subscribe(result => {
      this.usersData.data[i] = result; // <--- not updated in table aftrer close modal
      this.table.renderRows();
    });
  }
}

推荐阅读