如何在Ag-grid分页中通过count/pageSize方式设置总页数?
Hey there! Let's walk through how to set up Ag-Grid pagination where you control the total pages using count/pageSize, and load data only when the pagination changes. I’ve implemented this exact flow before, so here’s a step-by-step breakdown:
1. Configure Your Grid Options First
Start by setting up core pagination settings in your gridOptions. You’ll need to enable pagination, disable auto-calculation of page sizes, define a default page size, and hook up the pagination change event.
this.gridOptions = { columnDefs: [/* Add your column definitions here */], rowData: [], // Turn on pagination pagination: true, // Set default number of items per page paginationPageSize: 10, // Disable auto page size calculation (we'll handle total pages manually) paginationAutoPageSize: false, // Trigger data load when user switches pages onPaginationChanged: this.handlePaginationChanged.bind(this), // Optional: Add handler if you let users adjust page size onPaginationPageSizeChanged: this.handlePageSizeChange.bind(this), // Add other grid configs as needed (e.g., row height, themes) };
2. Handle Pagination Changes & Load Data
The onPaginationChanged event fires whenever the user navigates to a new page. In this handler, you’ll fetch the relevant page data from your backend, calculate the total pages using totalCount/pageSize, then set it via api.setTotalPages().
async handlePaginationChanged() { const gridApi = this.gridOptions.api; // Ag-Grid uses 0-based page indexes—convert to 1-based for most backend APIs const currentPage = gridApi.paginationGetCurrentPage() + 1; const pageSize = gridApi.paginationGetPageSize(); try { // Fetch paginated data from your backend service const response = await yourDataService.fetchPaginatedItems({ page: currentPage, pageSize: pageSize }); const { data, totalCount } = response; // Update the grid with the new page's data gridApi.setRowData(data); // Calculate total pages (round up to cover all items) const totalPages = Math.ceil(totalCount / pageSize); // Set the total pages in the grid to update pagination controls gridApi.setTotalPages(totalPages); } catch (error) { console.error('Failed to load paginated data:', error); // Add user-facing error handling here (e.g., toast notification) } }
3. Bonus: Handle Page Size Changes
If you allow users to adjust how many items show per page, add a handler to reset to the first page and reload data with the new page size:
async handlePageSizeChange() { // Reset to the first page (0-based index) this.gridOptions.api.paginationGoToPage(0); // Reload data with the updated page size await this.handlePaginationChanged(); }
Quick Notes to Avoid Headaches
- Initial Data Load: Call
handlePaginationChanged()once when your component initializes (e.g., inmounted,ngOnInit, orcomponentDidMount), sinceonPaginationChangeddoesn’t fire automatically when the grid first loads. - Page Index Quirk: Remember Ag-Grid’s page index starts at 0—most backends expect 1-based page numbers, so adjust accordingly.
- Edge Case for Empty Data: If
totalCountis 0, settotalPagesto 1 to keep pagination controls from disappearing entirely.
内容的提问来源于stack exchange,提问作者Anurag Upadhyaya

