Home > front end >  Sorting Angular Material Table by Date column
Sorting Angular Material Table by Date column

Time:10-28

I have an interface with different types:

export interface PeriodicElement {
  name: string;
  position: number;
  refDate?: Date;
  refTime?: string;
  symbol: string;
  phone: string;
  email: string;
  url: string;
  note1: string;
  note2: string;
}

and I use the date pipe to show the refDate in a table column:

<!-- Reference Date Column -->
<ng-container matColumnDef="refDate">
  <th mat-header-cell *matHeaderCellDef mat-sort-header>Ref. Date</th>
  <td mat-cell *matCellDef="let element">{{element.refDate | date}}</td>
</ng-container>

but - after changing a date of a row through a material date picker - when I sort by "Ref. Date" the rows are not correctly sorted.

CodePudding user response:

after changing a date of a row through a material date picker

The issue happens because the internal representation of the item.refDate is a string e.g. 2021-10-24T22:00:00.000Z but the native date picker can transform the saved item.refDate into e.g. Mon Nov 01 2021 00:00:00 which is no longer correctly sorted.

To fix it, I've set up a custom sort as follows:

this.dataSource.sortingDataAccessor = (item, property) => {
    switch (property) {
      case 'refDate': {
          if (item.refDate) {
              return new Date(item.refDate);
          }
          return null;
      }
      default: {
        return item[property as keyof PeriodicElement] as any;
      }
    }
};

Notice the line return item[property as keyof PeriodicElement] as any; written so to overcome two kinds of errors:

both

error TS7053: Element implicitly has an 'any' type because expression of type 'string'can't be used to index type 'PeriodicElement'. No index signature with a parameter of type 'string' was found on type 'PeriodicElement'.

and

error TS2322: Type '(item: PeriodicElement, property: string) => string | number | Date | null | undefined' is not assignable to type '(data: PeriodicElement, sortHeaderId: string) => string | number'. 
  • Related