Search code examples
angularangular-material-6angular-material-table

The correct method of updating a MatTableDataSource in Angular 2 version 6


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

in the component.html

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

in the component.ts

dataSource = new MatTableDataSource();

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.

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 it's a lack of understanding on my behalf.


Solution

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

    Below is a code example:

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

    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.

    Using Angular Material 6.4.7.

    Hope this helps.