I am trying to sort a table by its columns. The problem occurs when I have to filter a result that is inside another.
I tried to access the property by bracket notation and dot notation but none gave results. Also placing the final node in matColumnDef but it fails because there are 2 columns with the same name.
<table mat-table [dataSource]="dataSource" matSort>
<!-- Element name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
</ng-container>
<!-- Username Column -->
<ng-container matColumnDef="user.name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Username </th>
<td mat-cell *matCellDef="let element"> {{element.user.name}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
displayedColumns definition:
displayedColumns = ['name', 'user.name'];
There is a dataSource example:
[
{
id: 2,
name: "Testing",
user: {
id: 1,
name: "User Testing",
username: "[email protected]"
}
},
{
id: 4,
name: "Testing_2",
user: {
id: 3,
name: "User Testing 2",
username: "[email protected]"
}
}
]
It was hard to find documentation on this, but it is possible by customizing the sortingDataAccessor of MatTableDataSource and a switch statement.
For example:
@ViewChild(MatSort) sort: MatSort;
ngOnInit() {
this.dataSource = new MatTableDataSource(yourData);
this.dataSource.sortingDataAccessor = (item, property) => {
switch(property) {
case 'project.name': return item.project.name;
default: return item[property];
}
};
this.dataSource.sort = sort;
}
Found here: Angular Material 2 DataTable Sorting with nested objects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With