Skip to content

Commit 1b3c9f8

Browse files
committed
fix(paginator): update page index if invalid after length change
Updates the page index of a paginator if its length changed to something where the index isn't valid anymore (e.g. the user is on the last page and the amount of pages becomes smaller). Fixes #14520.
1 parent a58c725 commit 1b3c9f8

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/material/paginator/paginator.spec.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,30 @@ describe('MatPaginator', () => {
464464
expect(paginator.showFirstLastButtons).toBe(true);
465465
});
466466

467+
468+
it('should update the page index when switching to a smaller length', fakeAsync(() => {
469+
const fixture = createComponent(MatPaginatorApp);
470+
const instance = fixture.componentInstance;
471+
instance.length = 50;
472+
instance.pageSize = 10;
473+
instance.pageIndex = 4;
474+
fixture.detectChanges();
475+
476+
expect(instance.paginator.pageIndex).toBe(4);
477+
478+
instance.pageEvent.calls.reset();
479+
480+
instance.length = 10;
481+
fixture.detectChanges();
482+
tick();
483+
484+
expect(instance.paginator.pageIndex).toBe(0);
485+
expect(instance.pageEvent).toHaveBeenCalledWith(jasmine.objectContaining({
486+
previousPageIndex: 4,
487+
pageIndex: 0
488+
}));
489+
}));
490+
467491
});
468492

469493
function getPreviousButton(fixture: ComponentFixture<any>) {

src/material/paginator/paginator.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,18 @@ export class MatPaginator extends _MatPaginatorBase implements OnInit, OnDestroy
127127
get length(): number { return this._length; }
128128
set length(value: number) {
129129
this._length = coerceNumberProperty(value);
130+
131+
const maxPageIndex = Math.max(this.getNumberOfPages() - 1, 0);
132+
const currentPageIndex = this._pageIndex;
133+
134+
if (currentPageIndex > maxPageIndex && this.initialized) {
135+
// Needs to happen on the next tick, in order to avoid "changed after checked" errors.
136+
Promise.resolve().then(() => {
137+
this._pageIndex = maxPageIndex;
138+
this._emitPageEvent(currentPageIndex);
139+
});
140+
}
141+
130142
this._changeDetectorRef.markForCheck();
131143
}
132144
private _length = 0;

0 commit comments

Comments
 (0)