如何在ag-grid中显示无数据的固定Legal Entity分组
实现ag-grid固定显示无数据分组的方案
这个需求其实很常见,我给你两种实用的实现思路,你可以根据自己的场景选择:
方法一:预处理数据源,补充空条目(最易上手)
首先你得先定义好所有必须显示的Legal Entity列表,不管有没有数据都要展示的那种:
// 所有需要固定显示的Legal Entity const requiredLegalEntities = ['embr', 'ana', 'wi', 'zone3', 'zuna'];
接下来把API返回的原始数据和这个列表做匹配,给没有对应数据的实体补充一条空条目:
// 假设apiData是从API拿到的原始数据数组 const apiData = [ {legalEntity:"embr",description:"embr desc",amount:400}, {legalEntity:"ana",description:"ana desc",amount:20}, {legalEntity:"wi",description:"wi desc",amount:10} ]; // 处理成包含所有必要分组的数据源 const processedData = requiredLegalEntities.map(entity => { // 查找是否已有对应数据 const existingItem = apiData.find(item => item.legalEntity === entity); // 有就用原数据,没有就补空条目 return existingItem || { legalEntity: entity, description: '', amount: null }; });
然后把processedData作为ag-grid的rowData传入就行。
如果不想让空条目在分组里显示(只留分组头),可以加个行样式隐藏空行,还能顺便隐藏分组数量避免显示0:
const gridOptions = { columnDefs: [ {headerName:'Legal Entity',field:'legalEntity',enableRowGroup:true}, {headerName:'Description',field:'description'}, {headerName:'Amount',field:'amount'} ], // 隐藏空条目行 getRowStyle: params => { if (!params.data.description && params.data.amount === null) { return { display: 'none' }; } }, // 自定义分组列的显示 autoGroupColumnDef: { cellRendererParams: { suppressCount: true // 不显示分组后的条目数量 } }, rowData: processedData };
方法二:使用树形数据模式(更贴合空分组操作需求)
如果你的核心需求是让用户能选中空分组节点来新增条目,用ag-grid的树形数据模式会更直观,直接构建分组树结构:
const requiredLegalEntities = ['embr', 'ana', 'wi', 'zone3', 'zuna']; const apiData = [/* 你的API原始数据 */]; // 构建分组树,每个分组作为父节点,对应数据作为子节点 const groupTreeData = requiredLegalEntities.map(entity => ({ legalEntity: entity, // 标记为分组节点 __isGroupNode: true, // 匹配对应的数据作为子节点,没有就留空数组 children: apiData.filter(item => item.legalEntity === entity) }));
然后配置ag-grid启用树形数据:
const gridOptions = { treeData: true, animateRows: true, // 指定数据的路径(这里直接用legalEntity作为分组路径) getDataPath: data => [data.legalEntity], columnDefs: [ {headerName:'Legal Entity',field:'legalEntity'}, {headerName:'Description',field:'description'}, {headerName:'Amount',field:'amount'} ], rowData: groupTreeData };
这种方式下,空分组会直接显示成展开的空节点,用户可以直接选中这个节点,你只需要在新增条目的逻辑里,把新数据添加到对应节点的children数组,然后刷新网格就行:
// 示例:给zone3分组新增条目 const newEntry = { legalEntity: 'zone3', description: '新增的描述', amount: 100 }; // 找到对应的分组节点 const targetGroupNode = gridOptions.api.getRowNode('zone3'); if (targetGroupNode) { // 添加子节点 targetGroupNode.children.push(newEntry); // 刷新分组数据 gridOptions.api.refreshClientSideRowModel('group'); }
两种方法都能满足你的需求,方法一适合快速改造现有代码,方法二更适合后续要频繁操作分组节点的场景~
内容的提问来源于stack exchange,提问作者honunu
相关产品推荐
相关产品推荐

