首页 > 解决方案 > MatTable 不刷新更新

问题描述

mat-table我在对其数据执行更新操作后尝试刷新视图。但是,表视图仅在我第一次进行更新时正确刷新。每个后续更新操作都会延迟 1 个操作,如下所示:

  1. 更新第 1 行 -> 没有任何反应
  2. 更新第 2 行 -> 第 1 行得到更新
  3. 更新第 3 行 -> 第 2 行得到更新

等等...

该表使用 http.get 服务加载以获取数据。更新操作调用 http.post 服务来保存数据,随后调用该refreshData()方法。两种服务都按预期工作。

我正在使用ChangeDetectorRef强制更改检测。

零件:

dataSource: MatTableDataSource<IRegion> = new MatTableDataSource();

@ViewChild(MatSort) set content(sort: MatSort) {
    this.dataSource.sort = sort;
};

constructor(private regionService: RegionService, private changeDetectorRefs: ChangeDetectorRef) {}

ngOnInit() {
    this.populateRegions();
}

refreshData(){
    this.populateRegions();
}

populateRegions(){
    this.regionService.getRegions().subscribe({
        next: regions => {
            this.dataSource.data = regions;
            this.changeDetectorRefs.detectChanges();
        }
    });
}

我在这里做错了什么?

标签: angularangular-materialmat-table

解决方案


参考的使用RenderRows()方法mat-table

@ViewChild(MatTable, {static: false}) table : MatTable
this.table.renderRows()

或者重新创建数据源对象:

populateRegions(){
    this.regionService.getRegions().subscribe({
        next: regions => {
            this.dataSource = new MatTableDataSource(regions);
            this.changeDetectorRefs.detectChanges();
        }
    });
}

推荐阅读