Skip to content

Commit

Permalink
fix: update pagination pageOptions calculation logic (#3021)
Browse files Browse the repository at this point in the history
Co-authored-by: Akshat Patel <38994122+Akshat55@users.noreply.github.com>
  • Loading branch information
eduardmarcinco and Akshat55 authored Oct 8, 2024
1 parent 0532bd9 commit 75422dc
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
26 changes: 25 additions & 1 deletion src/pagination/pagination.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { TestBed } from "@angular/core/testing";
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { By } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { Component, OnInit } from "@angular/core";
Expand Down Expand Up @@ -150,4 +150,28 @@ describe("Pagination", () => {
expect(buttonBackward.disabled).toBe(true);
expect(element.componentInstance.currentPage).toBe(5);
});

/**
* Number of pages should always be 1 even if totalDataLength is greater than 0
*/
it("should recalculate pages when changing data", () => {
const fixture = TestBed.createComponent(Pagination);
const wrapper = fixture.componentInstance;
const model = new PaginationModel();
model.currentPage = 1;
model.pageLength = 5;
model.totalDataLength = 9;
wrapper.model = model;
fixture.detectChanges();
expect(wrapper.pageOptions).toEqual(Array(2));
model.totalDataLength = 2;
fixture.detectChanges();
expect(wrapper.pageOptions).toEqual(Array(1));
model.totalDataLength = 20;
fixture.detectChanges();
expect(wrapper.pageOptions).toEqual(Array(4));
model.totalDataLength = 0;
fixture.detectChanges();
expect(wrapper.pageOptions).toEqual(Array(1));
});
});
10 changes: 8 additions & 2 deletions src/pagination/pagination.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,8 +320,14 @@ export class Pagination {
}

get pageOptions() {
if (this.totalDataLength && this._pageOptions.length !== this.totalDataLength) {
this._pageOptions = Array(Math.ceil(this.totalDataLength / this.itemsPerPage));
/**
* Calculate number of pages based on totalDataLength and itemsPerPage.
* Even if totalDataLength is 0, numberOfPages should be always at least 1.
* New array will be constructed only if number of pages changes.
*/
const numberOfPages = Math.max(Math.ceil(this.totalDataLength / this.itemsPerPage), 1);
if (this._pageOptions.length !== numberOfPages) {
this._pageOptions = Array(numberOfPages);
}
return this._pageOptions;
}
Expand Down

0 comments on commit 75422dc

Please sign in to comment.