You should be able to do it your way as well, but you need to have a function to trigger change detection and table re-render rows.
@ViewChild(MatTable) table: MatTable<any>;
then you call
this.table.renderRows()
and depending on your change detection strategy you might need to also call
this.ref.detectChanges()
You must inject the change detector ref in your constructor then:
constructor(private ref: ChangeDetectorRef) {}
But then Angular material has this functionality built in, the documentation for this is quite excellent with quite a few up-to-date examples:
[URL]
Here's an example though, copy pasted from there:
<table matSort (matSortChange)="sortData($event)">
<tr>
<th mat-sort-header="name">Dessert (100g)</th>
<th mat-sort-header="calories">Calories</th>
<th mat-sort-header="fat">Fat (g)</th>
<th mat-sort-header="carbs">Carbs (g)</th>
<th mat-sort-header="protein">Protein (g)</th>
</tr>
<tr *ngFor="let dessert of sortedData">
<td>{{dessert.name}}</td>
<td>{{dessert.calories}}</td>
<td>{{dessert.fat}}</td>
<td>{{dessert.carbs}}</td>
<td>{{dessert.protein}}</td>
</tr>
</table>
sortedData: Dessert[];
constructor() {
this.sortedData = this.desserts.slice();
}
sortData(sort: Sort) {
const data = this.desserts.slice();
if (!sort.active || sort.direction === '') {
this.sortedData = data;
return;
}
this.sortedData = data.sort((a, b) => {
const isAsc = sort.direction === 'asc';
switch (sort.active) {
case 'name': return compare(a.name, b.name, isAsc);
case 'calories': return compare(a.calories, b.calories, isAsc);
case 'fat': return compare(a.fat, b.fat, isAsc);
case 'carbs': return compare(a.carbs, b.carbs, isAsc);
case 'protein': return compare(a.protein, b.protein, isAsc);
default: return 0;
}
});
}
}
function compare(a: number | string, b: number | string, isAsc: boolean) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}