Skip to content

Commit 75422dc

Browse files
fix: update pagination pageOptions calculation logic (#3021)
Co-authored-by: Akshat Patel <[email protected]>
1 parent 0532bd9 commit 75422dc

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

src/pagination/pagination.component.spec.ts

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { TestBed } from "@angular/core/testing";
1+
import { ComponentFixture, TestBed } from "@angular/core/testing";
22
import { By } from "@angular/platform-browser";
33
import { FormsModule } from "@angular/forms";
44
import { Component, OnInit } from "@angular/core";
@@ -150,4 +150,28 @@ describe("Pagination", () => {
150150
expect(buttonBackward.disabled).toBe(true);
151151
expect(element.componentInstance.currentPage).toBe(5);
152152
});
153+
154+
/**
155+
* Number of pages should always be 1 even if totalDataLength is greater than 0
156+
*/
157+
it("should recalculate pages when changing data", () => {
158+
const fixture = TestBed.createComponent(Pagination);
159+
const wrapper = fixture.componentInstance;
160+
const model = new PaginationModel();
161+
model.currentPage = 1;
162+
model.pageLength = 5;
163+
model.totalDataLength = 9;
164+
wrapper.model = model;
165+
fixture.detectChanges();
166+
expect(wrapper.pageOptions).toEqual(Array(2));
167+
model.totalDataLength = 2;
168+
fixture.detectChanges();
169+
expect(wrapper.pageOptions).toEqual(Array(1));
170+
model.totalDataLength = 20;
171+
fixture.detectChanges();
172+
expect(wrapper.pageOptions).toEqual(Array(4));
173+
model.totalDataLength = 0;
174+
fixture.detectChanges();
175+
expect(wrapper.pageOptions).toEqual(Array(1));
176+
});
153177
});

src/pagination/pagination.component.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -320,8 +320,14 @@ export class Pagination {
320320
}
321321

322322
get pageOptions() {
323-
if (this.totalDataLength && this._pageOptions.length !== this.totalDataLength) {
324-
this._pageOptions = Array(Math.ceil(this.totalDataLength / this.itemsPerPage));
323+
/**
324+
* Calculate number of pages based on totalDataLength and itemsPerPage.
325+
* Even if totalDataLength is 0, numberOfPages should be always at least 1.
326+
* New array will be constructed only if number of pages changes.
327+
*/
328+
const numberOfPages = Math.max(Math.ceil(this.totalDataLength / this.itemsPerPage), 1);
329+
if (this._pageOptions.length !== numberOfPages) {
330+
this._pageOptions = Array(numberOfPages);
325331
}
326332
return this._pageOptions;
327333
}

0 commit comments

Comments
 (0)