Skip to content

Commit 534af71

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 d22f48c commit 534af71

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/lib/paginator/paginator.spec.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,27 @@ describe('MatPaginator', () => {
414414
expect(getLastButton(fixture).hasAttribute('disabled')).toBe(true);
415415
});
416416

417+
it('should update the page index when switching to a smaller length', fakeAsync(() => {
418+
fixture.componentInstance.length = 50;
419+
fixture.componentInstance.pageSize = 10;
420+
fixture.componentInstance.pageIndex = 4;
421+
fixture.detectChanges();
422+
423+
expect(paginator.pageIndex).toBe(4);
424+
425+
fixture.componentInstance.pageEvent.calls.reset();
426+
427+
fixture.componentInstance.length = 10;
428+
fixture.detectChanges();
429+
tick();
430+
431+
expect(paginator.pageIndex).toBe(0);
432+
expect(fixture.componentInstance.pageEvent).toHaveBeenCalledWith(jasmine.objectContaining({
433+
previousPageIndex: 4,
434+
pageIndex: 0
435+
}));
436+
}));
437+
417438
});
418439

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

src/lib/paginator/paginator.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,18 @@ export class MatPaginator extends _MatPaginatorBase implements OnInit, OnDestroy
100100
get length(): number { return this._length; }
101101
set length(value: number) {
102102
this._length = coerceNumberProperty(value);
103+
104+
const maxPageIndex = Math.max(this.getNumberOfPages() - 1, 0);
105+
const currentPageIndex = this._pageIndex;
106+
107+
if (currentPageIndex > maxPageIndex && this.initialized) {
108+
// Needs to happen on the next tick, in order to avoid "changed after checked" errors.
109+
Promise.resolve().then(() => {
110+
this._pageIndex = maxPageIndex;
111+
this._emitPageEvent(currentPageIndex);
112+
});
113+
}
114+
103115
this._changeDetectorRef.markForCheck();
104116
}
105117
_length: number = 0;

0 commit comments

Comments
 (0)