You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Mat-Sort对嵌套结构JSON的Mat-Table列生效?

问题根源与解决方案

问题根源

MatTable自带的MatSort组件默认只会直接读取数据对象的顶层属性来做排序判断。你现在的questionCategoryName是嵌套在questionCategory对象里的,marksPerQuestion是嵌套在section对象里的——当你把questionCategory和section设为排序列时,MatSort会尝试直接比较这些子对象本身,而不是它们内部的目标字段,这就导致排序逻辑完全不符合预期,自然失效了。


解决方案:自定义排序访问器(Sorting Accessor)

我们需要给MatTableDataSource设置一个自定义的sortingDataAccessor,告诉它怎么去获取嵌套字段的值。具体操作如下:

1. 修改TypeScript代码

在你初始化dataSource之后,添加这段自定义访问器的代码:

this.dataSource.sortingDataAccessor = (item, property) => {
  switch(property) {
    // 针对嵌套字段返回具体要排序的值
    case 'questionCategory':
      return item.questionCategory.questionCategoryName;
    case 'section':
      return item.section.marksPerQuestion;
    // 其他顶层字段按默认逻辑处理
    default:
      return item[property];
  }
};

2. 完整的TS代码示例

getTableData() {
  this.columnsToDisplay = ['questionCategory', 'questionText', 'section'];
  this.adminService.getQuestion().subscribe(response => {
    this.QuestionData = response.questionList;
    this.dataSource = new MatTableDataSource<any>(this.QuestionData);
    this.length = this.QuestionData.length;

    // 新增自定义排序访问器
    this.dataSource.sortingDataAccessor = (item, property) => {
      switch(property) {
        case 'questionCategory':
          return item.questionCategory.questionCategoryName;
        case 'section':
          return item.section.marksPerQuestion;
        default:
          return item[property];
      }
    };

    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.isLoading = false;
  });
}

原理说明

MatSort默认的sortingDataAccessor逻辑是(item, property) => item[property],对于questionCategory这种列,它会直接取item.questionCategory这个对象,而不是里面的questionCategoryName。对象之间的比较逻辑根本不是我们需要的字符串/数字排序,所以才会失效。通过自定义访问器,我们直接返回需要排序的具体字段值,让MatSort能正确进行比较排序。

内容的提问来源于stack exchange,提问作者avishekdr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 21:23:11