在 angular 2 版本 6 中更新 MatTableDataSource 的正确方法 [英] The correct method of updating a MatTableDataSource in angular 2 version 6

查看:20
本文介绍了在 angular 2 版本 6 中更新 MatTableDataSource 的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单,它使用由 MatTableDataSource 提供的 mat-table 组件.

I have a listing that uses the mat-table component which is fed by the MatTableDataSource.

在 component.html 中

in the component.html

<table mat-table [dataSource]="dataSource" matSort>

在 component.ts 中

in the component.ts

dataSource = new MatTableDataSource();

当我点击删除一个项目时,在来自服务器的成功回调中,我通过重新实例化 MatTableDataSource(this.resources) 更新列表以反映新结果集,并像这样传入新结果集.这确实有效...

when I click to delete an item, on the success callback from the server, I update the list to reflect the new result set by reinstantiating the MatTableDataSource(this.resources) and pass in the new result set like so. This does work...

this.PHService.getResources().subscribe(resources => {
  this.resources = resources;
  this.dataSource = new MatTableDataSource(this.resources);
  this.dataSource.sort = this.sort;
});

然而,即使这有效,我觉得这是错误的.

However, even though this works, I feel this is wrong.

我读过一些文章说我必须扩展数据源?并调用 renderRows() 方法?我已经尝试过这个,但似乎无法让它在我的场景中工作.

I have read some articles that state I have to extend the datasource? and call the renderRows() method? I have tried this and I cannot seem to get it to work in my scenario.

我知道这是代表我缺乏理解.

I know its a lack of understanding on my behalf.

任何帮助/建议将不胜感激.

Any help / advice would greatly be appreciated.

提前致谢.

推荐答案

我找到了一个更好的方法,它无需使用 @ViewChild 属性装饰器注入 ChangeDetectorRefs 服务.

I have found a better method, that saves having to inject the ChangeDetectorRefs service by using the @ViewChild property decorator.

下面是一个代码示例:

@ViewChild(MatTable) table: MatTable<any>;

然后简单地调用该属性装饰器上的 renderRows() 方法,示例如下:

then simply call the renderRows() method on that property decorator, example below:

  refresh(): void{
    this.service.method().subscribe(resources => {
      this.dataSource.data = resources; 
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;
    });
    this.table.renderRows();
  }

这是我目前想到的最好的解决方案.

This is the best solution to this I have come up with that works so far for me.

使用 Angular Material 6.4.7.

Using Angular Material 6.4.7.

希望这会有所帮助.

这篇关于在 angular 2 版本 6 中更新 MatTableDataSource 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆