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!