Trying to sort the material table with date column , date format is 'MM/DD/YYYY ,h:mm A' , order of date is not by latest date and time. Anything which i missed from the below stackblitz code.
-
Can you upload the code to https://stackblitz.com/ ? – German Quinteros Jan 24 '20 at 03:13
-
https://stackblitz.com/edit/angular-matsordesc , here is the code. – vijay munnangi Jan 24 '20 at 03:24
2 Answers
The problem is the sort is sorting the date as type string
instead of type date
.
It works for me changing the ngAfterViewInit
for this:
ngAfterViewInit() {
this.dataSource.sort = this.sort;
this.dataSource.sortingDataAccessor = (item, property) => {
switch (property) {
case 'date': {
let newDate = new Date(item.date);
return newDate;
}
default: {
return item[property];
}
}
};
}
What we are doing here it's when the sort executes, in the case of the date we convert the item.date
from string to date. Then the sort executes the property date as a type date
.
Here I add a screenshot of https://stackblitz.com/edit/angular-matsordesc?file=src%2Fapp%2Fapp.component.ts where is working:

- 1,870
- 9
- 33
-
Still the same issue ,the order sort is not by today's date.and the item.date is undefined – vijay munnangi Jan 24 '20 at 22:29
-
That is strange. I tested in stackblitz.com/edit/angular-matsordesc and it works for me. Are you importing ```MatTableModule``` and ```MatTableModule``` in the module where has been defined your component? – German Quinteros Jan 25 '20 at 00:45
-
i just see it again here is the https://stackblitz.com/edit/angular-matsordesc?file=src%2Fapp%2Fapp.component.ts – vijay munnangi Jan 25 '20 at 01:30
-
I have just try it here: https://stackblitz.com/edit/angular-matsordesc?file=src%2Fapp%2Fapp.component.ts and it's working fine. I upload a Screenshot to my answer. – German Quinteros Jan 27 '20 at 15:26
In .ts file,
@ViewChild(MatSort, {static: true}) sort: MatSort;
this.sort.sort({ id: 'columnname', start: 'asc', disableClear: false })
case 'columnname': return ((a[sort.active] ? new Date(a[sort.active]).getTime() : 1) < (b[sort.active] ? new Date(b[sort.active]).getTime() : 1) ? 1 : -1) * (isAsc ? -1 : 1);
German Quinteros, your solution works fine.This ia another solution for the same issue. But in both cases, when there is ngIf* in a <mat-cell then there will be some empty values in between sorted values of the column.

- 1
- 1