如何不使用sortingDataAccessor实现mat-sort-header按日期字符串排序?
问题描述
我有一个带排序表头的Angular Material DataTable,其中两列为日期字符串类型,目前通过以下代码可正常实现排序:
HTML代码:
<ng-container *ngFor="let column of columns"[matColumnDef]="column"> <th mat-header-cell *matHeaderCellDef [mat-sort-header]=column.property>{{column.header}}</th> <td mat-cell *matCellDef="let item">{{item[column.property]}}</td> </ng-container>
TS代码:
this.dataSource.sortingDataAccessor = (item, property) => { switch (property) { case 'from': return new Date(item.from); case 'to': return new Date(item.to); default: return item[property]; } };
官方文档说明:
Note that if the data properties do not match the column names, or if a more complex data property accessor is required, then a custom sortingDataAccessor function can be set to override the default data accessor on the MatTableDataSource.
我希望不再使用sortingDataAccessor,仅修改HTML代码来实现正确排序,应该如何操作?另外我猜测是否可以通过类似“column.sortProp”的方式,针对日期字段替换mat-sort-header的配置?
解决方案
完全可以通过你猜测的思路实现,核心是给列配置添加排序用的属性映射,同时在mat-sort-header中动态指定排序依据,具体操作如下:
- 更新列配置结构
在TS代码的columns数组中,给每个列对象添加sortAccessor字段:日期字段指定转换为Date对象的逻辑,普通字段直接返回原属性值。示例如下:
columns = [ { header: '开始日期', property: 'from', sortAccessor: (item) => new Date(item.from) }, { header: '结束日期', property: 'to', sortAccessor: (item) => new Date(item.to) }, { header: '名称', property: 'name', sortAccessor: (item) => item.name } // 其他列配置... ];
- 修改HTML模板
将mat-sort-header的绑定值从column.property改为包含id和sortAccessor的对象,其中id和matColumnDef保持一致,确保列标识正确:
<ng-container *ngFor="let column of columns" [matColumnDef]="column.property"> <th mat-header-cell *matHeaderCellDef [mat-sort-header]="{ id: column.property, sortAccessor: column.sortAccessor }"> {{ column.header }} </th> <td mat-cell *matCellDef="let item">{{ item[column.property] }}</td> </ng-container>
- 核心原理
mat-sort-header支持传入配置对象,其中sortAccessor字段会替代默认的数据提取逻辑。日期字段通过该函数直接返回Date类型值,确保排序时按时间顺序而非字符串顺序处理;普通字段则保持默认的属性值返回,不影响原有排序逻辑。
完成以上修改后,即可移除TS中的sortingDataAccessor配置,仅通过HTML和列配置调整实现正确的日期排序。
内容的提问来源于stack exchange,提问作者Stranger
相关产品推荐
相关产品推荐

