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

Angular5+Material5分页器页面事件中length异常递增问题求助

Angular 5 + Material 5.0.4: Paginator Length Increments Unexpectedly (Works on StackBlitz, Fails Locally)

Environment

  • Angular 5
  • Angular Material 5.0.4

Issue Description

I'm using MatTable paired with MatPaginator, fetching data via HTTP requests from my backend. When the page change event fires, I trigger a new request to load the corresponding page of data.

Here's the confusing behavior:

  • When I log my custom totalLength variable (which stores the total record count returned by the server), it stays consistent and correct across page switches.
  • But the length property of the MatPaginator instance is unexpectedly incrementing with every page change—for example, if the actual total is 100, after a few page switches it might show 200, 300, or higher.
  • The exact same code with identical dependency versions works flawlessly on StackBlitz, but the issue reproduces reliably in my local development environment.

Demo of Paginator Length Unexpectedly Increasing

Troubleshooting Steps & Solutions

Having dealt with similar environment-specific Angular Material quirks before, here are the most likely fixes to try:

1. Verify Paginator Length Assignment Logic

First, double-check that you're directly assigning the server's total count to the paginator's length property, not accidentally adding to it. It's easy to slip up with += instead of =:

// ❌ Wrong - this causes incremental length bloat
// this.paginator.length += res.totalCount;

// ✅ Correct - overwrite with the actual total from server
this.http.get('/api/your-data-endpoint', { params: pageParams }).subscribe(response => {
  this.dataSource.data = response.data;
  this.totalLength = response.totalCount;
  this.paginator.length = this.totalLength; // Explicit, one-time assignment
});

2. Fix Local Dependency Version Mismatches

Even if your package.json lists 5.0.4 for Material, local nested dependencies or cached packages might be causing inconsistencies. Clean your local environment to reset:

# Delete node_modules and lock file
rm -rf node_modules
rm package-lock.json

# Clear npm cache and reinstall dependencies
npm cache clean --force
npm install

Also, ensure your package.json uses exact versions (no ^ or ~ prefixes) for Angular and Material packages to prevent unintended minor version upgrades:

"dependencies": {
  "@angular/material": "5.0.4",
  // ... other exact version declarations
}

3. Check for Duplicate Paginator Event Subscriptions

If you're subscribing to the paginator.page event multiple times (e.g., in ngOnInit and another lifecycle hook, or due to accidental component re-renders), each subscription will trigger the data load and potentially update the paginator length multiple times.

Use a cleanup mechanism to avoid duplicate subscriptions:

import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

private destroy$ = new Subject<void>();

ngOnInit() {
  // Use takeUntil to automatically unsubscribe when component is destroyed
  this.paginator.page.pipe(takeUntil(this.destroy$)).subscribe(event => {
    this.loadPageData(event.pageIndex, event.pageSize);
  });
}

ngOnDestroy() {
  this.destroy$.next();
  this.destroy$.complete();
}

4. Address Change Detection Issues

If your component uses ChangeDetectionStrategy.OnPush, the paginator's view might not sync properly with the updated length value. Try:

  • Temporarily switching back to ChangeDetectionStrategy.Default to see if the issue resolves
  • If you need to keep OnPush, manually trigger change detection after updating the paginator:
import { ChangeDetectorRef } from '@angular/core';

constructor(private cdr: ChangeDetectorRef) {}

loadPageData(pageIndex: number, pageSize: number) {
  this.http.get(...).subscribe(response => {
    this.dataSource.data = response.data;
    this.totalLength = response.totalCount;
    this.paginator.length = this.totalLength;
    this.cdr.markForCheck(); // Force change detection to sync view
  });
}

5. Disable Local HTTP Request Caching

Sometimes local dev servers cache HTTP responses, leading to stale totalCount values. Add a cache-busting parameter to your request:

const pageParams = new HttpParams()
  .set('page', pageIndex.toString())
  .set('size', pageSize.toString())
  .set('_t', Date.now().toString()); // Timestamp to prevent caching

this.http.get('/api/your-data-endpoint', { params: pageParams }).subscribe(...);

You can also disable cache directly in your browser's DevTools (Network tab > check "Disable cache") to rule out this possibility.


内容的提问来源于stack exchange,提问作者Narendra Singh Rathore

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:21:00