Utilizing a mat table to display paginated data fetched from my API presents a challenge when the page is refreshed after the user navigates away. Instead of displaying the initial first page, I aim to show the second page.
To achieve this, I store the pageIndex in local storage and retrieve it upon refresh. While my API successfully fetches the second page, the pagination options appear incorrect:
Mat Page Options After Refresh
The displayed range shows 1-8 instead of 9-15, with navigation incorrectly set to the last page.
Below is the snippet of my HTML code:
<mat-paginator
class="mat-paginator-sticky"
[hidden]="pageLength <= pageSizeOptions[0]"
[pageSizeOptions]="pageSizeOptions"
[showFirstLastButtons]="true"
[length]="pageLength"
[pageIndex]="page.pageIndex"
(page)="pageChange($event)"
aria-label="Select page of users"
></mat-paginator>
And here are snippets of the TypeScript file:
constructor() {
// Retrieve and set the current page index
const savedPageIndex = localStorage.getItem('currentPageIndex');
if (savedPageIndex) {
this.page.pageIndex = +savedPageIndex;
}
}
Attempting a solution, I made the following changes:
ngAfterViewInit(): void {
setTimeout(() => {
if (this.dataSource) {
this.dataSource.sort = this.sort;
this.paginator.pageIndex = this.page.pageIndex;
this.paginator.pageSize = this.page.pageSize;
this.paginator.length = this.pageLength;
this.paginator._changePageSize(this.paginator.pageSize);
this.dataSource.paginator = this.paginator;
}
});
}
I am seeking guidance on how to properly adjust the page range label and next/previous buttons.