[SOLVED] How to sorting by date string with mat-sort-header?


I have a case table constructed with angular.material and I need to add sorting by date. But my date is a string type, and so sorting incorrectly. How to overriding default mat-sort-header behavior. And it’s possible?

<div class="example-container mat-elevation-z8">
    <mat-table #table [dataSource]="dataSource" matSort>

        <!-- Reg Date Column -->
        <ng-container matColumnDef="regDate">
            <mat-header-cell *matHeaderCellDef mat-sort-header> Reg Date </mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element.regDate}} </mat-cell>
        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>

And on TS side:

sort: MatSort;
set appBacon(sort : MatSort) {
    this.sort = sort;
    this.dataSource.sort = this.sort;
dataSource = new MatTableDataSource([]);


Here is the solution:-
Pass Date object in sortingDataAccessor function which will make sure date objects will get sorted correctly.

this.dataSource.sortingDataAccessor = (item, property) => {
  switch (property) {
    case 'fromDate': return new Date(item.fromDate);
    default: return item[property];

MatTableDataSource has sortingDataAccessor which we can customize as per our need.

Answered By – Sagar Kharche

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *