Skip to content

Commit 9febcbe

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 5b3e846 commit 9febcbe

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/material/paginator/paginator.spec.ts

+21
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,27 @@ describe('MatPaginator', () => {
413413
expect(getLastButton(fixture).hasAttribute('disabled')).toBe(true);
414414
});
415415

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

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

src/material/paginator/paginator.ts

+12
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
private _length = 0;

0 commit comments

Comments
 (0)