如何使用mat-sort-header按日期字符串排序? [英] How to sorting by date string with mat-sort-header?

查看:199
本文介绍了如何使用mat-sort-header按日期字符串排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用angular.material构造的案例表,我需要按日期添加排序.但是我的日期是string类型,因此排序不正确.如何覆盖默认的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>
        </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函数中传递Date对象,以确保日期对象将正确排序.

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具有sortingDataAccessor,我们可以根据需要对其进行自定义.

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

这篇关于如何使用mat-sort-header按日期字符串排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆