Skip to content

Commit

Permalink
fix(paginator): update page index if invalid after length change
Browse files Browse the repository at this point in the history
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 angular#14520.
  • Loading branch information
crisbeto committed Dec 24, 2018
1 parent d22f48c commit 534af71
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/lib/paginator/paginator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,27 @@ describe('MatPaginator', () => {
expect(getLastButton(fixture).hasAttribute('disabled')).toBe(true);
});

it('should update the page index when switching to a smaller length', fakeAsync(() => {
fixture.componentInstance.length = 50;
fixture.componentInstance.pageSize = 10;
fixture.componentInstance.pageIndex = 4;
fixture.detectChanges();

expect(paginator.pageIndex).toBe(4);

fixture.componentInstance.pageEvent.calls.reset();

fixture.componentInstance.length = 10;
fixture.detectChanges();
tick();

expect(paginator.pageIndex).toBe(0);
expect(fixture.componentInstance.pageEvent).toHaveBeenCalledWith(jasmine.objectContaining({
previousPageIndex: 4,
pageIndex: 0
}));
}));

});

function getPreviousButton(fixture: ComponentFixture<any>) {
Expand Down
12 changes: 12 additions & 0 deletions src/lib/paginator/paginator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,18 @@ export class MatPaginator extends _MatPaginatorBase implements OnInit, OnDestroy
get length(): number { return this._length; }
set length(value: number) {
this._length = coerceNumberProperty(value);

const maxPageIndex = Math.max(this.getNumberOfPages() - 1, 0);
const currentPageIndex = this._pageIndex;

if (currentPageIndex > maxPageIndex && this.initialized) {
// Needs to happen on the next tick, in order to avoid "changed after checked" errors.
Promise.resolve().then(() => {
this._pageIndex = maxPageIndex;
this._emitPageEvent(currentPageIndex);
});
}

this._changeDetectorRef.markForCheck();
}
_length: number = 0;
Expand Down

0 comments on commit 534af71

Please sign in to comment.