Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 494
Adamski Avatar asked Jan 16 '19 16:01

Adamski


People also ask

What is mat-table in ANGULAR?

The mat-table provides a Material Design styled data-table that can be used to display rows of data. This table builds on the foundation of the CDK data-table and uses a similar interface for its data input and template, except that its element and attribute selectors will be prefixed with mat- instead of cdk- .


Video Answer


2 Answers

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.

like image 155
Adamski Avatar answered Nov 16 '22 02:11

Adamski


Create new MatTableDataSource object once on component init, then add array that is incoming to dataSource.data

dataSource.data is array of data that should be rended by table,where each object represent one row,so you not creating new instance of object on every change.

ChangeDetectorRef can be used. It is looking for changes in a given component.

 constructor(private changeDetectorRefs: ChangeDetectorRef) {}

 refresh(){
  this.PHService.getResources().subscribe(resources => {

     this.dataSource.data = resources;
     this.dataSource.sort = this.sort;
  });
    this.changeDetectorRefs.detectChanges();
 }
like image 42
Nenad Radak Avatar answered Nov 16 '22 03:11

Nenad Radak