From 75422dc4e80671dae65c8a5da909f4a926422fdc Mon Sep 17 00:00:00 2001 From: Eduard Marcinco Date: Tue, 8 Oct 2024 20:02:31 +0200 Subject: [PATCH] fix: update pagination pageOptions calculation logic (#3021) Co-authored-by: Akshat Patel <38994122+Akshat55@users.noreply.github.com> --- src/pagination/pagination.component.spec.ts | 26 ++++++++++++++++++++- src/pagination/pagination.component.ts | 10 ++++++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/pagination/pagination.component.spec.ts b/src/pagination/pagination.component.spec.ts index abffb6cc06..c683fa256a 100644 --- a/src/pagination/pagination.component.spec.ts +++ b/src/pagination/pagination.component.spec.ts @@ -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"; @@ -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)); + }); }); diff --git a/src/pagination/pagination.component.ts b/src/pagination/pagination.component.ts index 1ba4a535c6..0308baa8cc 100644 --- a/src/pagination/pagination.component.ts +++ b/src/pagination/pagination.component.ts @@ -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; }