[英]Sorting Angular Material Table by Date column
我有一個不同類型的界面:
export interface PeriodicElement {
name: string;
position: number;
refDate?: Date;
refTime?: string;
symbol: string;
phone: string;
email: string;
url: string;
note1: string;
note2: string;
}
我使用日期管道在表列中顯示refDate
:
<!-- 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>
但是 - 通過材料日期選擇器更改行的日期后 - 當我按“參考日期”排序時,行沒有正確排序。
通過物料日期選擇器更改行的日期后
發生此問題是因為item.refDate
的內部表示是一個字符串,例如2021-10-24T22:00:00.000Z
但本機日期選擇器可以將保存的item.refDate
轉換為例如Mon Nov 01 2021 00:00:00
不再正確排序。
為了解決這個問題,我設置了一個自定義排序如下:
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;
}
}
};
注意行return item[property as keyof PeriodicElement] as any;
這樣寫是為了克服兩種錯誤:
兩個都
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'.
和
error TS2322: Type '(item: PeriodicElement, property: string) => string | number | Date | null | undefined' is not assignable to type '(data: PeriodicElement, sortHeaderId: string) => string | number'.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.