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

如何在Angular AG Grid中对表格内的对象数组进行分组?

Angular AG Grid 实现对象数组的嵌套分组展示

针对你遇到的「AG Grid grouping-custom-group-columns仅支持字符串数组,无法处理对象数组分组」的问题,结合你提供的数据结构和截图需求,最适合的方案是使用Master-Detail(主从表)模式来实现主行展开显示子对象数组的效果,具体实现步骤如下:

核心思路

你的数据结构是「主数据 + 嵌套子对象数组」(比如每个facility对应多条cdm记录),这种场景下用AG Grid的Master-Detail可以完美匹配截图里的展开展示需求,而非普通分组功能。

具体实现代码

1. 模板配置

<ag-grid-angular
  style="width: 100%; height: 600px;"
  class="ag-theme-alpine"
  [rowData]="rowData"
  [columnDefs]="columnDefs"
  [masterDetail]="true"
  [detailCellRendererParams]="detailCellRendererParams"
></ag-grid-angular>

2. 组件逻辑

import { Component } from '@angular/core';
import { ColDef } from 'ag-grid-community';

@Component({
  selector: 'app-facility-grid',
  templateUrl: './facility-grid.component.html',
  styleUrls: ['./facility-grid.component.css']
})
export class FacilityGridComponent {
  // 你的示例数据(可替换为接口请求数据)
  rowData = [
    {
      "id": 1,
      "unit":"01111", 
      "coid":"03111", 
      "facilityName":"abc company", 
      "market":"Charleston", 
      "mcMarket":"Carolina", 
      "production":"02/01/23", 
      "inactive":"5/01/23",
      "cdm": [{
        "id": 1,
        "cdmDate":"10/01/23", 
        "cdmPct":"8.00", 
        "exclusions":"250, 252"
      },
      {
        "id": 2,
        "cdmDate":"11/01/23", 
        "cdmPct":"9.50", 
        "exclusions":"251"
      }] 
    }
  ];

  // 主表列定义
  columnDefs: ColDef[] = [
    { field: 'unit', headerName: 'Unit', flex: 1 },
    { field: 'coid', headerName: 'COID', flex: 1 },
    { field: 'facilityName', headerName: 'Facility Name', flex: 2 },
    { field: 'market', headerName: 'Market', flex: 1 },
    { field: 'mcMarket', headerName: 'MC Market', flex: 1 },
    { field: 'production', headerName: 'Production Date', flex: 1 },
    { field: 'inactive', headerName: 'Inactive Date', flex: 1 }
  ];

  // 子表配置:渲染cdm对象数组
  detailCellRendererParams = {
    detailGridOptions: {
      columnDefs: [
        { field: 'cdmDate', headerName: 'CDM Date', flex: 1 },
        { field: 'cdmPct', headerName: 'CDM Percentage', flex: 1 },
        { field: 'exclusions', headerName: 'Exclusions', flex: 1 }
      ],
      defaultColDef: { flex: 1 }
    },
    // 传递子数据给子表
    getDetailRowData: (params: any) => {
      params.successCallback(params.data.cdm);
    }
  };
}

注意事项

  • grouping-custom-group-columns功能设计初衷是针对同一层级数据的维度分组(比如用字符串数组作为分组键),并不适合展示嵌套的对象数组数据,不要硬套。
  • 如果需要自定义子表的样式或交互,可以在detailCellRendererParams里添加更多配置,比如自定义渲染组件、设置子表高度等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 22:31:19