简体   繁体   中英

Sorting Angular Material Table by Date column

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.

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 eg 2021-10-24T22:00:00.000Z but the native date picker can transform the saved item.refDate into eg 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'. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM