Angular Pagination Showing Incorrect Page Count as "1-10 of 10" After Moving to Next Page Even with Accurate Total Item Count

Encountering an issue with Angular Material's MatPaginator where it shows "1-10 of 10" after moving to the second page, despite receiving correct total item count from the API. Pagination functions correctly on the initial page, but fails to update upon switching pages. Using Angular 17 with standalone components and struggling to determine the root cause, as logs appear accurate.

    export class BattlesDashboardComponent implements OnInit, AfterViewInit {

  displayedColumns: string[] = ['id', 'title', 'views', 'platform', 'likes'];
  dataSource = new MatTableDataSource<Battle>();
  totalItems = 0;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  constructor(private battlesService: BattlesService) {}

  ngOnInit() {}

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;

    this.loadBattles();

    this.paginator.page.subscribe(() => this.loadBattles());
  }

  loadBattles() {
    const pageIndex = this.paginator.pageIndex;
    const pageSize = this.paginator.pageSize;

    this.battlesService.getBattles(pageIndex + 1, pageSize).subscribe(result => {
      this.dataSource.data = result.data;
      this.totalItems = result.totalItems;
      this.paginator.length = this.totalItems;

      console.log(`Total Items: ${this.totalItems}`);
      console.log(`Loaded Battles: ${this.dataSource.data.length}`);
    }, error => {
      console.error("Error loading data:", error);
    });
  }
}

Pagination operates smoothly on the first page, logging correct total items at 717 and displaying 10 items as expected. However, upon moving to the second page, the paginator erroneously displays "1-10 of 10", despite the console confirming that totalItems remains 717.

The Logs:

 ____ getBattles ____
battles.service.ts:26 Total Items Header: 717
battles.service.ts:27 Total Items Parsed: 717
battles-dashboard.component.ts:58 Total Items: 717
battles-dashboard.component.ts:59 Loaded Battles: 10
core.mjs:30066 Angular hydrated 28 component(s) and 410 node(s), 0 component(s) were skipped. Learn more at https://angular.dev/guide/hydration.
battles.service.ts:19  ____ getBattles ____
battles.service.ts:26 Total Items Header: 717
battles.service.ts:27 Total Items Parsed: 717
battles-dashboard.component.ts:58 Total Items: 717
battles-dashboard.component.ts:59 Loaded Battles: 10

A workaround involves using setTimeout for proper functionality, though not considered ideal. Curious if Angular's hydration process could be causing issues or seeking alternate solutions. Any insights are appreciated!

Thank you in advance!

Answer №1

Utilizing pagination through an API requires your paginator to function independently. Therefore, the line below should be eliminated:

//exclude this line
this.dataSource.paginator = this.paginator;

Additionally, it's important to handle table sorting as well. A useful example that includes filtering and loading can be found on StackOverflow. If filtering is your main focus, you can implement something similar to the code snippet below afterViewInit:

ngAfterViewInit() {
    const sort = this.sort.sortChange.pipe(
      tap(() => this.paginator.firstPage())
    );
    merge(sort, this.paginator.page)
      .pipe(
        switchMap(res => {
          const pageIndex = this.paginator.pageIndex;
          const pageSize = this.paginator.pageSize;
          return this.battlesService.getBattles(pageIndex + 1,
                                                pageSize,
                                                this.sort.active,
                                                this.sort.direction)
        }))
      .subscribe((res: any[]) => {
           this.dataSource.data = result.data;
           this.totalItems = result.totalItems;
           this.paginator.length = this.totalItems;      });
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Strategies for Creating a Test Suite for RepositoryFactory in Vue.js/Nuxt.js

Summary of RepositoryFactory Implementation An implementation of the RepositoryFactory pattern has been carried out for API connection in a Vue.js/Nuxt.js application. For more details, refer to this article: here hogeRepository.ts import { NuxtAxiosInst ...

When you switch to a different URL within the same tab, the session storage will be automatically cleared

My current web application is experiencing an issue with session storage. Whenever I navigate to a different URL within the same tab, it seems like the session storage is being cleared. Let me walk you through the situation: I initially store some data ...

Tips for Resolving Capacitor Initialization Error in Angular Version 13.x

I've been working on integrating Capacitor into my Angular 13.x project. Successfully completed the first step: npm install @capacitor/core npm install @capacitor/cli --save-dev Encountering an error when trying to run the Capacitor Initialize comman ...

Imported modules are not being blocked by APP_INITIALIZER

In my Angular application (version 6.0.0), I am working on setting up runtime configuration using APP_INITIALIZER to pull in the configurations. While consulting various articles and Stack Overflow questions, such as this one and that one, I have managed t ...

Can you explain the key distinction between the backtick (`) and the ampersand-hash-39

I am completely new to TypeScript, JavaScript, and Angular. As I follow some tutorials, I often encounter code snippets like the one below: class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return `(${this.x}, ${th ...

Managing component composition in React/TypeScript: What's the best way to approach it?

I am brand new to the world of typescript, so please be patient with me. My objective is to transform this react component: interface ButtonProps {...} const Button: React.FC<ButtonProps> = ({ children, href, value as = 'button', ...

"Exploring the power of Angular6's RxJs MergeMap for handling

Currently, I am making one service call (getEmp()), and along with that, I am making two additional calls in parallel. Everything is working fine, but I need to receive the response of the first call (getEmp()). In the code below, inside the return map f ...

What is the reason buttons in mat-menus do not submit?

I have implemented a mat-menu to showcase a list of choices for the user. The objective is to trigger the submission of my formGroup when a user selects an option from the menu. dropdown.component.html <form [formGroup]="myForm" (ngSubmit)=onSubmit(my ...

Is there a way to retrieve the latitude and longitude values using a plugin and then make a web service call in Ionic with Angular 5?

I am currently trying to retrieve the latitude and longitude coordinates of a location by using geocode in Angular 5 within the Ionic framework. Once I have obtained the lat long, I intend to pass it to my service. The issue I am facing is that my service ...

Tips for managing an index signature in a basic object

I'm attempting to transform the received numerical status into a corresponding string for the user interface like this: {statuses[job.status]} const statuses = { 1: "Processing", 2: "Done", 3: "Aborted", 4: " ...

Exploring ways to conduct a thorough scan of object values, inclusive of nested arrays

My goal is to extract all values from an object. This object also includes arrays, and those arrays contain objects that in turn can have arrays. function iterate(obj) { Object.keys(obj).forEach(key => { console.log(`key: ${key}, value: ${o ...

Issue with Angular 9 Router's CanActivate not functioning properly in conjunction with redirects

Scenario: I aim to send logged in users to /dashboard and non-logged in users to /landing. Initial approach: { path: '**', redirectTo: '/dashboard', canActivate: [AuthGuard], }, { path: '**', redire ...

RC7 is missing the necessary HTTP_PROVIDERS for the resolveAndCreate HTTP method in Angular2

During the time of RC4, I was able to create my own custom http instance using a function like this: export function createHTTP(url:string, headers?:Headers){ let injector = ReflectiveInjector.resolveAndCreate([ myHttp, {provide:'defaultUrl ...

A novel RxJS5 operator, resembling `.combineLatest`, yet triggers whenever an individual observable emits

I am searching for a solution to merge multiple Observables into a flattened tuple containing scalar values. This functionality is similar to .combineLatest(), but with the added feature that it should emit a new value tuple even if one of the source obser ...

Attempting to sort data with AngularJS

I'm currently working on implementing 'order by' functionality in my Angular app. Here's what I've attempted: <div *ngFor = "let movie of webService.movie_list | async | orderBy:'Year'"> However, when testing it ...

Displaying code within an Angular 2 template

Working on an Angular 2 project and facing a challenge in displaying C# code within the template, which may later be styled with syntax highlighter. The issue arises when attempting to insert the C# code into the Angular 2 template, resulting in template ...

Tips for integrating Typescript Definition files with Visual Studio 2017

I have a challenge with my ASP.NET Core 2.0 application where I am attempting to incorporate TypeScript and jQuery. While TypeScript integration has been successful, I am facing issues with jQuery as it does not provide me with intellisense. Despite trying ...

Version 2.0.0 of Angular working with Karma to offer Router capabilities

When a test requires an instance of the `Router`, simply providing the `Router` itself is not sufficient: import {Router} from '@angular/router'; import {it, inject, beforeEachProviders} from '@angular/core/testing'; import {Compo ...

Error: Failed to retrieve the name property of an undefined value within the Array.forEach method

Upon pressing the button to display the task pane, I encountered an error message in the console window that reads: "Uncaught (in promise) TypeError: Cannot read property 'name' of undefined". This error persists and I am unable to resolve or com ...

The Material UI Datagrid is failing to display any data

I'm currently facing a challenge that has left me scratching my head. I've implemented Material UI Datagrids, but for some reason, I can't get it to populate with data, and the reason eludes me. Even though the Component profiler shows that ...