我有一个用 angular.material
构造的案例表,我需要添加按日期排序。但是我的日期是 string
类型,所以排序不正确。如何覆盖默认的 mat-sort-header
行为。这可能吗?
<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>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
</div>
在 TS 端:
sort: MatSort;
@ViewChild(MatSort)
set appBacon(sort : MatSort) {
this.sort = sort;
this.dataSource.sort = this.sort;
}
dataSource = new MatTableDataSource([]);
最佳答案
这是解决方案:- 在 sortingDataAccessor 函数中传递日期对象,这将确保日期对象正确排序。
this.dataSource.sortingDataAccessor = (item, property) => {
switch (property) {
case 'fromDate': return new Date(item.fromDate);
default: return item[property];
}
};
MatTableDataSource 具有 sortingDataAccessor,我们可以根据需要对其进行自定义。
关于angular - 如何使用 mat-sort-header 按日期字符串排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49603499/