The correct method of updating a MatTableDataSource in angular 2 version 6
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();
}
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.