Angular Material Table Sort with nested objects
January 18, 2023 · 2 min readLucian CiobanuI've recently noticed that material sorting while the property we're displaying in a material table is nested does not always work as expected. So, in the following html we can see the nested object and after that it's important to change the sortingDataAccessor once we have assigned values to dataSource.data as such:
<mat-table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="product">
<mat-header-cell *matHeaderCellDef mat-sort-header>Product Name</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.product.name}}</mat-cell>
</ng-container>
<ng-container matColumnDef="productType">
<mat-header-cell *matHeaderCellDef mat-sort-header>Product Type</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.productType.name}}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
In the ts file, right after having all the data from the BE do the following:
displayedColumns: string[] = ['product', 'productType'];
private getData() {
const getData = this.service.getData.subscribe(
(result) => {
if (result) {
this.dataSource.data = result;
this.dataSource.sortingDataAccessor = (object, property) => {
switch (property) {
case "product":
return object.product.name;
case "productType":
return object.productType.name;
default:
return object[property];
}
};
} else {
this.showError();
}
},
() => {
this.showError();
});
}
Hope this helped!
Cheers,
Lucian

Web Development & Software Delivery