Reputation: 21
I am working on displaying a table with sorting using angular material. I am able to get the sorted data for columns: 'customer name' and 'Validity Date' but the column='Route' is not getting sorted. This is my code, In html:
<table mat-table [dataSource]="dataSource" matSort class="width100">
<ng-container matColumnDef="customerName">
<th mat-header-cell mat-sort-header *matHeaderCellDef> Customer Name </th>
<td mat-cell *matCellDef="let element"> {{element.customerName}} </td>
</ng-container>
<ng-container matColumnDef="validityDate">
<th *matHeaderCellDef mat-sort-header mat-header-cell> Validity Date </th>
<td mat-cell *matCellDef="let element"> {{element.dateOfValidity | date: 'dd-MMM-yyyy'}} </td>
</ng-container>
<ng-container matColumnDef="route">
<th *matHeaderCellDef mat-sort-header mat-header-cell> Route </th>
<td mat-cell *matCellDef="let row"> {{row.oPortCountryCode}}, {{row.oPortCode}} >>
{{row.dPortCountryCode}}, {{row.dPortCode}}</td>
</ng-container>
</table>
In .ts file:
public dataSource: MatTableDataSource<QuotationModel>;
ngOnInit() {
this.service.getList().subscribe(resp => {
this.dataSource = new MatTableDataSource<QuotationModel>(resp.items);
this.dataSource.sort = this.sort;
this.dataSource.sortingDataAccessor = (item, property) => {
switch (property) {
case 'validityDate':
const newDate = new Date(item.dateOfValidity);
return newDate;
default:
return item[property];
}
};
});
}
And the model is:
export interface QuotationModel{
customerName: string;
dateOfValidity: Date;
oPortCountryCode: string;
oPortCode:string;
dPortCountryCode:string;
dPortCode:string;
}
Upvotes: 0
Views: 1662
Reputation: 1997
In your case the sorting accessor will try to sort by the property route
as it is your matColumnDef. Add a case to your sorting accessor which returns the same value as you display and it will sort by this column alphabetical.
ngOnInit() {
this.service.getList().subscribe(resp => {
this.dataSource = new MatTableDataSource<QuotationModel>(resp.items);
this.dataSource.sort = this.sort;
this.dataSource.sortingDataAccessor = (item, property) => {
switch (property) {
case 'validityDate':
const newDate = new Date(item.dateOfValidity);
return newDate;
case 'route':
return item.oPortCountryCode + ", " + item.oPortCode + " >> " + item.dPortCountryCode + ", " + item.dPortCode;
default:
return item[property];
}
};
});
}
Upvotes: 1