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

使用ag-grid服务端行模型分页时切换页面选中状态丢失问题咨询

解决AG Grid Server Side Row Model分页时选中状态丢失的问题

核心原因

AG Grid的Server Side Row Model在切换分页时,会销毁当前页的行DOM及对应的行实例,默认不会保留跨页的选中状态,导致切页后之前的选中记录被清空。要解决这个问题,需要手动基于行的唯一标识维护全局选中集合,而非依赖行实例本身。

具体实现步骤

1. 配置网格的唯一ID与选中模式

确保网格指定行的唯一标识字段,同时开启多选模式:

gridOptions = {
  rowModelType: 'serverSide',
  rowSelection: 'multiple',
  getRowId: params => params.data.id, // 替换为你的数据唯一ID字段
  // 其他网格配置...
};

2. 维护全局选中ID集合

在组件中声明变量存储所有选中行的唯一ID:

selectedRowIds = new Set<number>(); // 根据ID类型调整,比如string

3. 监听选中变化,同步全局集合

重写onSelectionChanged事件,手动更新选中ID集合,避免默认行为清空跨页选中:

onSelectionChanged() {
  const currentSelectedRows = this.gridApi.getSelectedRows();
  const currentPageRowIds = this.gridApi.getRenderedNodes().map(node => node.data.id);

  // 移除当前页中取消选中的ID
  currentPageRowIds.forEach(id => {
    if (!currentSelectedRows.some(row => row.id === id)) {
      this.selectedRowIds.delete(id);
    }
  });

  // 添加当前页中新选中的ID
  currentSelectedRows.forEach(row => {
    this.selectedRowIds.add(row.id);
  });
}

4. 数据加载完成后恢复选中状态

在Server Side数据加载完成后,手动恢复对应行的选中状态:

onServerSideDataLoaded(params) {
  // 等待网格渲染完成后执行
  setTimeout(() => {
    this.gridApi.forEachNode(node => {
      if (this.selectedRowIds.has(node.data.id)) {
        node.setSelected(true);
      }
    });
  }, 0);
}

如果使用ServerSideDatasource,可在getRows方法的成功回调中触发上述恢复逻辑。

5. 自定义全选逻辑(可选)

若需要支持跨页全选,需重写表头全选的默认行为:

headerCheckboxSelection = () => {
  return {
    checkboxSelection: true,
    headerCheckboxSelection: true,
    onHeaderCheckboxChanged: e => {
      const isAllSelected = e.checked;
      this.gridApi.forEachNode(node => {
        node.setSelected(isAllSelected);
        isAllSelected ? this.selectedRowIds.add(node.data.id) : this.selectedRowIds.delete(node.data.id);
      });
    }
  };
};

关键注意事项

  • getRowId必须配置正确,每行要有唯一且稳定的标识,这是跨页跟踪选中状态的基础。
  • 禁止依赖行实例(如RowNode)存储选中状态,分页切换后这些实例会被销毁。
  • 恢复选中状态的逻辑要放在DOM渲染完成后执行,确保行节点已生成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:53:26