Closed
Description
Documentation Feedback
When retrieving data asynchronously (e.g. from a REST service, see example below), if I reinstanciate the MatTableDataSource
object I use in the MatTable component, everything I do works fine except sorting.
example:
//...
export class TableSortingExample implements AfterViewInit {
dataSource = new MatTableDataSource();
constructor(/*...*/) {
this.http.get("myservice").pipe(
tap((response) => {
this.dataSource = new MatTableDataSource(response); // <- reinstanciating the Datasource.
// Breaks sorting.
})
).subscribe();
}
@ViewChild(MatSort) sort: MatSort;
ngAfterViewInit() {
this.dataSource.sort = this.sort;
}
}
If I do something like this, clicking on the sort arrows has no effect.
Whereas if I use something like that:
//...
export class TableSortingExample implements AfterViewInit {
dataSource = new MatTableDataSource();
constructor(/*...*/) {
this.http.get("myservice").pipe(
tap((requests) => {
this.requests.data = requests; // <- Mutate reference to `data` property of the Datasource.
// Works fine.
})
).subscribe();
}
@ViewChild(MatSort) sort: MatSort;
ngAfterViewInit() {
this.dataSource.sort = this.sort;
}
}
Then everything works. This took me several hours to figure out, and I would probably never have found out, wouldn’t it have been for this. I think this should be documented.
Context:
Angular & Angular Material versions : 16.1.7
Affected documentation page
https://material.angular.io/components/table/overview#sorting