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

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

问题描述

我有一个用 angular.material 构造的案例表,我需要添加按日期排序.但是我的日期是 string 类型,所以排序不正确.如何覆盖默认的 mat-sort-header 行为.有可能吗?

<mat-table #table [dataSource]="dataSource" matSort><!-- 注册日期列--><ng-container matColumnDef="regDate"><mat-h​​eader-cell *matHeaderCellDef mat-sort-header>注册日期</mat-h​​eader-cell><mat-cell *matCellDef="let element">{{element.regDate}} </mat-cell></ng-容器><mat-h​​eader-row *matHeaderRowDef="displayedColumns"></mat-h​​eader-row><mat-row *matRowDef="let row; columns:displayedColumns;"></mat-row></mat-table>

在 TS 方面:

排序:MatSort;@ViewChild(MatSort)设置 appBacon(排序:MatSort){this.sort = 排序;this.dataSource.sort = this.sort;}数据源 = 新的 MatTableDataSource([]);

解决方案

解决方案如下:-在 sortingDataAccessor 函数中传递 Date 对象,这将确保日期对象正确排序.

this.dataSource.sortingDataAccessor = (item, property) =>{开关(属性){case 'fromDate': return new Date(item.fromDate);默认值:返回项目[属性];}};

MatTableDataSource 具有 sortDataAccessor,我们可以根据需要对其进行自定义.

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>

And on TS side:

sort: MatSort;
@ViewChild(MatSort)
set appBacon(sort : MatSort) {
    this.sort = sort;
    this.dataSource.sort = this.sort;
}
dataSource = new MatTableDataSource([]);

解决方案

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 has sortingDataAccessor which we can customize as per our need.

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

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