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

Utilizing a constant in setting the slotLabelFormat

I am attempting to configure the slotLabelFormat options in a React TypeScript project When I directly set slotLabelFormat={{ hour: "2-digit", minute: "2-digit", omitZeroMinute: false, meridiem: "short" }}, TypeScript compile ...

How can I access the parameter value for the tooltip callback function within echarts?

I am attempting to retrieve the value for this specific Apache EChart from within the callback function of the tooltip formatter. When I manually input the value, the formatting function operates correctly: formatter: (params:any) => `$ ${Math.round(pa ...

Vue textarea not accepting null values

My current setup includes the following dependencies: - "vue": "3.2.26", - "vee-validate": "4.5.6", - "typescript": "4.5.4" While working on a textarea field in vue3, I encountered an issue Here's a snippet with vee-validate integration import { Fie ...

How to trigger a click event in React using TypeScript and material-ui library

Currently, I am facing an issue when trying to update the value of material-ui TextFields from the store. When manually typing inside the field, everything works fine as expected with the handleChange() and handleBlur() functions handling the events. Howev ...

What is the best way to resolve the "unknown" type using AxiosError?

I'm currently working on developing a customized hook for axios, but I've encountered the following error: Argument of type 'unknown' is not assignable to parameter of type 'SetStateAction<AxiosError<unknown, any> | unde ...

Angular Error: Unable to access the 'title' property of an undefined value

Error Message Showing on Console for post-create.component.html ERROR Message: TypeError: Cannot read property 'title' of undefined at PostCreateComponent_Template (template.html:13) I suspect the issue is related to this line - console.log(for ...

Storing the typeof result in a variable no longer aids TypeScript in type inference

Looking at the code snippet below: export const func = (foo?: number) => { const isNumber = typeof foo === 'number'; return isNumber ? Math.max(foo, 0) : 0; }; A problem arises when TypeScript complains that you cannot apply undefined to ...

Unexpected disappearance of form control in reactive form when using a filter pipe

Here is a reactive form with an array of checkboxes used as a filter. An error occurs on page render. Cannot find control with path: 'accountsArray -> 555' The filter works well, but the error appears when removing any character from the fi ...

Watching - transforming / combining

I am a beginner when it comes to working with Observables. Here's the Effect that I am using: My goal is to dispatch the PositionUpdateAction or PositionFailedAction before the SunriseSunsetAction is dispatched. Currently, what happens is that the r ...

Exploring abstract classes for diverse implementation strategies?

Consider the following scenario: export abstract class Button { constructor(public config: IButton) {} abstract click(); } Now, we have a concrete class: class ButtonShowMap extends Button { private isShow = false; constructor(public config: IBu ...

Show a table row based on a specific condition in Angular

I'm having this issue with the tr tag in my code snippet below: <tr *ngFor="let data of list| paginate:{itemsPerPage: 10, currentPage:p} ; let i=index " *ngIf="data.status=='1'" > <td> </td> <td> ...

Using react-google-charts to create visually appealing dual-Y stacked bar charts

I am currently working on developing a bar chart with specific criteria in mind. My data follows the format: [month, region, totalSalesForCompanyA, totalSalesForCompanyB] I have successfully implemented the following charts: A dual-Y bar chart where mo ...

The property 'item' is not found within the specified type 'IntrinsicAttributes & RefAttributes<Component<{}, any, any>>'. Error code: 2322

"react": "^16.12.0", "typescript": "^4.0.3", "next": "^9.4.4" The error being raised by typescript is related to the <Item item={item} key={item.id} urlReferer={urlReferer} /> prop used ...

Encountering an error in Jest with TypeScript (Backend - Node/Express) that reads "Cannot use import statement outside a module

Currently, I am in the process of developing Jest tests for a Node/Express TypeScript backend. Recently, I came across the concept of global test setup which I am integrating to streamline the usage of variables and function calls that are repeated in all ...

Recursive rendering of tree components in React

I am facing a challenge in rendering tree items recursively using React. I have been struggling to achieve the desired outcome as calling treeRender(children) seems to alter the data structure when a folder is encountered for the first time. I am curious a ...

Cannot trigger event ascn.onchange does not exist as a function

Need to trigger the onChange function and pass parameters within it. Here's what I have tried: setTimeout(function() { document.getElementById(input.key)?.onchange({}) }, 200); Encountering the following error message: cn.onchange is not a function ...

Storing data locally in Angular applications within the client-side environment

As I delve into Angular and TypeScript, I've encountered a perplexing issue. Let's say I have two classes - Employee and Department. On the server-side, I've established a Many-To-One relationship between these entities using Sequelize: db. ...

Guide to Rolling a Set of 5 Dice

I am looking to develop a game involving 5 dice. I have already created a function to roll one die using a random method, but I am unsure how to extend this functionality to the remaining four dice without having to create a separate method for each one. ...

The Angular JavaScript page successfully compiles, yet displays only a blank screen

I am facing an issue with my Angular app where it compiles successfully, but the HTML page appears blank and my application is not displaying properly. I have encountered similar problems in the past which were often related to Imports, but this time I&apo ...

React Native - The size of the placeholder dictates the height of a multiline input box

Issue: I am facing a problem with my text input. The placeholder can hold a maximum of 2000 characters, but when the user starts typing, the height of the text input does not automatically shrink back down. It seems like the height of the multiline text ...