Why is the Last Page display on pagination showing as 3 instead of 2 per items?

When working on Angular 13, I encountered an issue with applying pagination numbers like 1, 2, 3, etc.

The problem I faced was that the last page Number should be 2, but it is displaying as 3. Why is this happening?

To investigate the issue, I tested my web API and found that the last page number is indeed 2, so why is it being displayed as 3?

Below is the JSON data returned when running the API:

https://localhost:7235/api/items?pageNumber=0

   {
    "items": [
        {
            "id": 3,
            "itemNameER": "قلم",
            "itemNameEN": "pen",
            "description": "1"
        },
        {
            "id": 4,
            "itemNameER": "قلم",
            "itemNameEN": "pencil",
            "description": null
        },
        {
            "id": 5,
            "itemNameER": "قلم",
            "itemNameEN": "pen2",
            "description": null
        },
        {
            "id": 8,
            "itemNameER": "car",
            "itemNameEN": "car",
            "description": "1"
        },
        {
            "id": 9,
            "itemNameER": "mobile",
            "itemNameEN": "mobile",
            "description": "1"
        }
    ],
    "pager": {
        "numberOfPages": 2,
        "currentPage": 1,
        "totalRecords": 6
    }
}

Based on the above data, the number of pages is 2, so why is it displaying 3?

Here is a snippet from the component.html file:

<table id="customers">
  <tr>
    <th>Id</th>
    <th>ItemNameAR</th>
    <th>ItemNameEN</th>
    <th>Description</th>
  </tr>
  <tr 
    *ngFor="
      let item of items
        | paginate
          : {
              itemsPerPage: pager?.numberOfPages,
              currentPage: pager?.currentPage,
              totalItems: pager?.totalRecords
            }
    "
  >
  <td>{{item.id}}</td>
  <td>{{item.itemNameAR}}</td>
  <td>{{item.itemNameEN}}</td>
  <td>{{item.description}}</td>
  </tr>
</table>

<pagination-controls
  previousLabel="Prev"
  nextLabel="Next"
  [responsive]="true"
  (pageChange)="onPageChanged($event)" 
></pagination-controls>

And here is part of the component.ts file:

export class ItemsComponent implements OnInit {
  items?: ItemsData[] | undefined;
  pager:any;
  currentItem = null;
  pageNumber:number=1;
  constructor(private erpservice:ErpServiceService) { }

  ngOnInit(): void {
    this.retrieveAllItems();
  }
  onPageChanged(pageNumber: number) {
    this.retrieveAllItems(pageNumber);
  }
  
  retrieveAllItems(pageNumber: number = 0): void {
    this.erpservice.getAll(pageNumber)
      .subscribe(
        data => {
        this.items=data.items;
        this.pager=data.pager;
        console.log(this.pager);
        },
        error => {
          console.log(error);
        });
  }
}

This is how the services.ts looks like:

getAll(pageNumber: number): Observable<DataWrapper> {
    let params = new HttpParams();

    if (pageNumber)
      params = params.append('pageNumber', pageNumber);

    let httpOptions = {
        params: params
    };
    return this.http.get<DataWrapper>(baseUrl,httpOptions);
  }

Lastly, the models used in this project are defined as follows:

export interface ItemsData {
    id:number;
    itemNameER:string;
    itemNameAR:string;
    itemNameEN:string;
    description:string;
}
export interface DataWrapper {
    items: ItemsData[];
    pager:Pager;
}

export interface Pager {
    numberOfPages:number;
    currentPage:number;
    totalRecords:number;
}

As for the final result obtained, you can view it here.

Answer №1

I managed to resolve the problem by setting

itemsPerPage in the component.ts file

export class ItemsComponent implements OnInit {
  itemsPerPage:number=5;

Then, in the component.html file, I assigned it for pagination as shown below:

<tr 
    *ngFor="
      let item of items
        | paginate
          : {
              itemsPerPage: itemsPerPage,
              currentPage: pager?.currentPage,
              totalItems: pager?.totalRecords
            }
    "
  >

The issue was that initially, I mistakenly set the number of pages instead of items per page. But now, my problem is resolved.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding 30 Days to a Date in Typescript

Discovering Typescript for the first time, I'm attempting to calculate a date that is (X) months or days from now and format it as newDate below... When trying to add one month: const dateObj = new Date(); const month = dateObj.getUTCMonth() + 2; con ...

Observable<void> fails to trigger the subscriber

I am currently facing a challenge with implementing a unit test for an Observable in order to signal the completion of a process. While there is no asynchronous code in the logout function yet, I plan to include it once the full logic is implemented. The m ...

Implementing a ReactJS component with a TypeScript interface for displaying an Alert box message using Material

I have a MUI Alert box in my application where I am trying to change the message inside with an href URL. However, when I use the herf tag, it shows as text instead of a link. How can I make it display as an actual link? In the code below, when I click th ...

Strict mode error occurs when attempting to assign a value to ngComponentOutlet that is incompatible with the type of the lazy-loaded component

I am attempting to implement lazy loading for a component in Angular 11 (strict mode) using guidance from this tutorial. Dealing with strict mode has been challenging as there are very few resources available that cater to it. The goal is to have a compon ...

Retrieve the Ionic storage item as a string

My issue is related to the code snippet below: this.storage.get('user') Upon execution, it returns the following object: t {__zone_symbol__state: null, __zone_symbol__value: Array(0)} I am uncertain about how to handle this object. Is there ...

Enhancing the aesthetic appeal of Angular2 Google Maps

Hey there, I'm a newcomer to Angular2/Typescript and I've been working on styling a map in my Angular2 project. I integrated a map using the Angular2 Google Maps Components, but I'm having trouble with applying styles through the undocumente ...

Tips for maintaining the original data type while passing arguments to subsequent functions?

Is there a way to preserve generic type information when using typeof with functions or classes? For instance, in the code snippet below, variables exampleNumber and exampleString are of type Example<unknown>. How can I make them have types Example& ...

Limiting the character input in ion-textarea within Ionic 2: A step-by-step guide

In my Ionic 2 application, I need to limit user comments to less than 500 characters in a text area. What is the best way to implement this restriction? ...

Angular - Navigate to Login Page post registration and display a confirmation message

As a newcomer to Angular, I am currently working on an Angular and Spring Boot application. So far, I have created components for user login and registration along with validation features. Now, my goal is to redirect the user to the login page upon succes ...

What is the process of mapping in a React Element?

I have encountered an issue while trying to implement my parameter, which is an array of objects. The error message I received states: Parameter 'option' implicitly has an 'any' type.ts(7006) I am unable to determine the cause of this ...

Removing scrollbar from table in React using Material UI

I successfully created a basic table using react and material UI by following the instructions found at: https://material-ui.com/components/tables/#table. The table is functioning properly, but I am finding the scrollbar to be a bit inconvenient. https:// ...

The issue of declaration merging and complications with nested node_modules

Here is the structure I am working with: @my/app node_modules @types/angular @types/angular-translate @my/library node_modules @types/angular The issue arises from the fact that @types/angular-translate extends the definitions of @types/angular ...

What is the reason behind the lag caused by setTimeout() in my application, while RxJS timer().subscribe(...) does not have the same

I am currently working on a component that "lazy loads" some comments every 100ms. However, I noticed that when I use setTimeout for this task, the performance of my application suffers significantly. Here is a snippet from the component: <div *ngFor ...

Refreshing Components upon updates to session storage - Angular

Currently, I am in the process of developing a build-a-burger website using Angular. The ingredients and inventory need to be updated dynamically based on the selected location. Users can choose the location from a dropdown menu in the navigation bar. The ...

Writing Data to Google Cloud Firestore Map using NextJS and Typescript with nested objects

I could use some assistance. I'm developing an application using NextJS (React), TypeScript, and Google Cloud Firestore. Everything seems to be working fine so far. However, I'm facing an issue with storing the address and phone number in a neste ...

Array updating using the foreach method in Angular

Hey everyone, I've encountered an error that seems to be related to scope and I could use some advice. I'm currently looping through an array and trying to push the results to another array. However, when I attempt to push the results to public m ...

Creating a definition for the use of sweet alerts within a service and incorporating them through

Implementing sweet alert for displaying alert messages in angularJS2/typescript. Due to the repetitive nature of this code in different parts of the application, a service was created. @Injectable() export class AlertMessageService { constructor(pr ...

Angular issue: Readonly or disabled input fields not submitting data

Struggling with creating a form in Angular 2 to submit dynamically generated values from a service. The goal is to calculate the equivalent amount of bitcoin for X chilean pesos using Angular's http module to fetch the price. However, facing an issue ...

Understanding Scope in TypeScript

Recently, I developed a sample application in Node.js which utilizes pg-promise to execute queries on a Postgres database. I encapsulated this functionality within a class named PostgresDataAccess. However, I encountered an issue while trying to access t ...

The element is implicitly imparted with an 'any' type due to the incapability of utilizing an expression of type 'number' to index the type '{}'. This error occurs in the context of VUEJS

I have encountered an issue that I have been struggling to resolve despite trying numerous solutions. The problem arises while working on a project using Vue. Here is how I have structured my data: data(){ return{ nodes: {}, edges:{}, ...