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

Ag-Grid如何读取全部分页指定单元格数据并存储到数组

实现方案

AG Grid 开启分页模式后,gridApi 默认仅加载当前页的行数据,无法直接通过该API读取其他分页的记录,可根据你的数据源模式选择对应实现方式:

场景1:前端分页(全量数据已提前加载到前端,仅由AG Grid做分页渲染)

有两种实现方式可选:

  • 方式1:提前维护全量数据源,在数据加载完成后直接处理
    首先在组件中新增变量存储全量数据源,修改后代码如下:
    export class AppComponent {
      gridApi: any;
      columnApi: any;
      title = 'AgGridPro';
      allRowData: any[] = []; // 新增:存储全量表格数据
      constructor(private httpClient : HttpClient){}
    
      column = [
        {
          "headerName": "Name",
          "field": "name",
          sortable: true,
          editable: true
        },
        {
          "headerName": "Mobile",
          "field": "mobile"
        },
        {
          "headerName": "Age",
          "field": "age"
        },
        {
          field: 'age',
          minWidth: 120,
          aggFunc: 'sum',
        },
        {
          "headerName": "Address",
          "field": "Address"
        }
      ]
    
      onGridReady(params: any) {
        this.gridApi = params.api;
        this.columnApi = params.columnApi;
        // 数据加载逻辑可在此处触发
        this.loadTableData();
      }
    
      // 示例:表格数据加载逻辑
      loadTableData() {
        this.httpClient.get('你的数据接口地址').subscribe((res: any) => {
          this.allRowData = res;
          // 给AG Grid赋值数据源
          this.gridApi.setRowData(this.allRowData);
          // 执行name字段处理逻辑
          this.processNameData();
        })
      }
    
      // name字段处理逻辑
      processNameData() {
        const allNames: string[] = [];
        const invalidRecords: any[] = [];
    
        this.allRowData.forEach(row => {
          // 空字符串、null、undefined都判定为name字段异常
          if (!row?.name) {
            invalidRecords.push(row);
            return;
          }
          allNames.push(row.name);
        })
        // 此处可对两个结果数组做后续业务处理
        console.log('所有name列数据:', allNames);
        console.log('name为空的异常记录:', invalidRecords);
      }
    }
    
  • 方式2:直接通过AG Grid API遍历全量数据(无需自己维护数据源)
    前端分页场景下,可通过forEachNodeAfterFilterAndSort方法遍历所有行,不受分页限制,代码如下:
    processNameData() {
      const allNames: string[] = [];
      const invalidRecords: any[] = [];
    
      this.gridApi.forEachNodeAfterFilterAndSort((node: any) => {
        const row = node.data;
        if (!row?.name) {
          invalidRecords.push(row);
          return;
        }
        allNames.push(row.name);
      })
    }
    

场景2:服务端分页(每次切换分页才请求后端接口,前端仅存当前页数据)

该场景下前端没有全量数据,无法通过gridApi获取其他分页的记录,必须后端配合提供全量数据查询接口,调用接口拿到全部200条数据后,再按照上述逻辑处理即可。

注意:不建议循环切换分页拉取所有页数据,该方式性能差且容易出现数据不一致问题,优先选择后端提供全量接口的方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:45:00