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

AgGrid服务端模式处理全选时选中行数返回0,求正确获取方法

AgGrid服务端模式下获取当前页全选的选中行方案

问题原因

当开启headerCheckboxSelectionCurrentPageOnly: true并点击当前页全选时,AgGrid不会将当前页所有节点加入getServerSideSelectionState()的toggledNodes数组,而是通过rowSelection.selectAllCurrentPage: true这个状态标记来表示全选当前页。你之前只读取toggledNodes.length,自然会得到0。

正确处理方式

需要同时处理单个节点勾选和当前页全选两种状态,结合当前页渲染数据来获取完整的选中行:

代码示例

const onSelectionChangedHandler = (event: SelectionChangedEvent) => {
  const selectionState = event.api.getServerSideSelectionState();
  let selectedRows: any[] = [];

  // 1. 收集单独勾选的节点数据
  if (selectionState?.toggledNodes) {
    selectionState.toggledNodes.forEach(nodeId => {
      const node = event.api.getRowNode(nodeId);
      if (node?.isSelected()) { // 确保节点处于选中状态,过滤取消勾选的残留ID
        selectedRows.push(node.data);
      }
    });
  }

  // 2. 处理当前页全选的情况
  if (selectionState?.rowSelection?.selectAllCurrentPage) {
    // 获取当前页所有渲染的节点数据
    const currentPageNodes = event.api.getRenderedNodes();
    let currentPageRows = currentPageNodes.map(node => node.data);

    // 排除全选后手动取消勾选的节点
    const deselectedNodeIds = selectionState?.toggledNodes?.filter(nodeId => {
      const node = event.api.getRowNode(nodeId);
      return node && !node.isSelected();
    }) || [];

    if (deselectedNodeIds.length > 0) {
      currentPageRows = currentPageRows.filter(row => {
        const rowNodeId = event.api.getRowNodeId(row);
        return !deselectedNodeIds.includes(rowNodeId);
      });
    }

    selectedRows = [...selectedRows, ...currentPageRows];
  }

  console.log('选中行数:', selectedRows.length);
  console.log('选中行数据:', selectedRows);
};

关键说明

  • getServerSideSelectionState()的结构:服务端模式下,选择状态分为toggledNodes(单独勾选/取消的节点ID数组)和rowSelection(批量选择标记,如selectAllCurrentPage、selectAll)
  • getRenderedNodes():获取当前页正在渲染的所有节点,适合当前页全选场景下获取行数据
  • 处理取消勾选:全选后如果手动取消部分节点,这些节点ID会被加入toggledNodes,需要从当前页数据中排除这些节点

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 18:21:32