Ada*_*ski 10 angular angular-material-6 mat-table
我有一个清单,它使用由 MatTableDataSource 提供的 mat-table 组件。
在 component.html
<table mat-table [dataSource]="dataSource" matSort>
Run Code Online (Sandbox Code Playgroud)
在 component.ts
dataSource = new MatTableDataSource();
Run Code Online (Sandbox Code Playgroud)
当我点击删除一个项目时,在来自服务器的成功回调上,我通过重新实例化 MatTableDataSource(this.resources) 更新列表以反映新的结果集,并像这样传入新的结果集。这确实有效...
this.PHService.getResources().subscribe(resources => {
this.resources = resources;
this.dataSource = new MatTableDataSource(this.resources);
this.dataSource.sort = this.sort;
});
Run Code Online (Sandbox Code Playgroud)
然而,即使这有效,我觉得这是错误的。
我读过一些文章,指出我必须扩展数据源?并调用 renderRows() 方法?我已经尝试过这个,但我似乎无法让它在我的场景中工作。
我知道这是代表我缺乏理解。
任何帮助/建议将不胜感激。
提前致谢。
我找到了一个更好的方法,它无需使用 @ViewChild 属性装饰器注入 ChangeDetectorRefs 服务。
下面是一个代码示例:
@ViewChild(MatTable) table: MatTable<any>;
Run Code Online (Sandbox Code Playgroud)
然后简单地调用该属性装饰器上的 renderRows() 方法,示例如下:
refresh(): void{
this.service.method().subscribe(resources => {
this.dataSource.data = resources;
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;
});
this.table.renderRows();
}
Run Code Online (Sandbox Code Playgroud)
这是迄今为止我提出的对我有用的最佳解决方案。
使用角材料 6.4.7。
希望这可以帮助。
在组件初始化时创建新的 MatTableDataSource 对象,然后添加传入 dataSource.data 的数组
dataSource.data 是应该按表渲染的数据数组,其中每个对象代表一行,因此您不会在每次更改时都创建新的对象实例。
可以使用 ChangeDetectorRef。它正在寻找给定组件中的更改。
constructor(private changeDetectorRefs: ChangeDetectorRef) {}
refresh(){
this.PHService.getResources().subscribe(resources => {
this.dataSource.data = resources;
this.dataSource.sort = this.sort;
});
this.changeDetectorRefs.detectChanges();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12297 次 |
| 最近记录: |