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

Angular动态数据表格排序实现求助:dataSource已用作DTO数组

Angular Material 表格动态数据排序实现方案

核心思路

你不需要替换原有的dataSource(DTO数组变量),只需通过MatTableDataSource作为中间层封装该数组,同时处理嵌套字段的排序逻辑即可。


1. 调整 TypeScript 代码

新增MatTableDataSource类型变量用于绑定表格,同时自定义排序数据访问器处理嵌套字段:

import { MatTableDataSource } from '@angular/material/table';

// 保留原DTO数组变量
dataSource: ChartofAccountsDTO[] = [];
// 新增表格专用数据源
tableDataSource = new MatTableDataSource<ChartofAccountsDTO>();
@ViewChild(MatSort, {static: true}) sort: MatSort;

ngOnInit() {
  // 替换为你实际的数据加载逻辑(比如API请求)
  this.loadChartData().then(() => {
    // 将原DTO数组赋值给表格数据源
    this.tableDataSource.data = this.dataSource;
    // 关联排序组件
    this.tableDataSource.sort = this.sort;

    // 自定义排序数据访问器,处理嵌套字段取值
    this.tableDataSource.sortingDataAccessor = (item, property) => {
      switch(property) {
        case 'classification':
          return item.groupClassificationDTO.classificationDTO.nameClassification;
        case 'subClassification':
          return item.groupClassificationDTO.subClassificationDTO.nameSubClassification;
        // 其他列需要排序时,可在此添加对应逻辑
        default:
          return item[property as keyof ChartofAccountsDTO];
      }
    };
  });
}

// 模拟数据加载函数
private loadChartData(): Promise<void> {
  return new Promise(resolve => {
    // 这里替换为你实际的数据获取代码
    this.dataSource = [
      // 你的ChartofAccountsDTO实例数据
    ];
    resolve();
  });
}

2. 修改 HTML 代码

仅需将表格的[dataSource]绑定改为新增的tableDataSource,其余结构保持不变:

<mat-table mat-table [dataSource]="tableDataSource" matSort>
  <ng-container matColumnDef="classification">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Classification </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.groupClassificationDTO.classificationDTO.nameClassification}} </mat-cell>
  </ng-container>  
  <ng-container matColumnDef="subClassification">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Sub-Classification </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.groupClassificationDTO.subClassificationDTO.nameSubClassification}} </mat-cell>
  </ng-container>                 
  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>

关键注意事项

  • 确保displayedColumns数组中包含classification和subClassification列名,否则排序表头不会生效
  • sortingDataAccessor是处理嵌套字段排序的核心,默认排序逻辑只能识别一级字段,嵌套字段需手动指定取值路径

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:15:37