Reputation: 899
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.
Upvotes: 14
Views: 20165
Reputation: 3242
this.dataSource.data = [];
this.dataSource = new MatTableDataSource(this.commonTableData);
Upvotes: 0
Reputation: 899
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.
Upvotes: 12
Reputation: 3688
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();
}
Upvotes: 6