AgGrid 中的行数

Row Count in AgGrid

我想在我的 AgGrid 中显示行数,但我遇到了问题。

    ngOnInit() { 
      console.log(this.gridOptions.api.getDisplayedRowCount());
    }

错误:

ERROR TypeError: Cannot read property 'getDisplayedRowCount' of undefined
    at ProjectListComponent.webpackJsonp../src/app/project-list/project-list.component.ts.ProjectListComponent.ngOnInit (project-list.component.ts:178)
    at checkAndUpdateDirectiveInline (core.js:12411)
    at checkAndUpdateNodeInline (core.js:13935)
    at checkAndUpdateNode (core.js:13878)
    at debugCheckAndUpdateNode (core.js:14771)
    at debugCheckDirectivesFn (core.js:14712)
    at Object.eval [as updateDirectives] (ProjectListComponent_Host.ngfactory.js? [sm]:1)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:14697)
    at checkAndUpdateView (core.js:13844)
    at callViewAction (core.js:14195)

Api AgGrid:

getDisplayedRowCount()  Returns the total number of displayed rows.

我不明白为什么我有这个问题...

(你提到了 ngOnInit 所以我假设你正在使用 Angular)
问题是 api 在 ngOnInit 中不可用。如果你需要网格 api.

,你应该监听 gridReady 事件

gridReady: ag-Grid has initialised. Use this event if, for example, you need to use the grid's API to fix the columns to size. Documentation

html:

<ag-grid-angular   style="width: 100%; height: 372px;"
  (gridReady)="onGridReady()">
</ag-grid-angular>

组件 ts:

onGridReady(params: any) {
  console.log('grid ready');
  console.log(this.gridOptions.api.getDisplayedRowCount());
}

您还应该记住 this site 上有一条注释:

Sometimes the gridReady grid event can fire before the Angular component is ready to receive it, so in an Angular environment its safer to rely on AfterViewInit instead before using the API.

尽管我在使用 gridReady 事件时从未遇到过任何问题。

如果您使用 ag-grid React 组件,则使用以下过程获取计数

<AgGridReact
    columnDefs={columnDefs}
    rowData={rowData}
    defaultColDef={defaultColDef}
    onGridReady={onGridReady}
></AgGridReact>


const onGridReady = (params) => {
        setRow(params.api.getDisplayedRowCount());
    };