简体   繁体   中英

How to calculate the current page if the items per page changes to a smaller number?

I have the following issue - I have a pagination, that shows which part of the records you are looking at.

For example:

Total Items: 100
Possible Items per Page: 10, 25

If I set the items per page to 10 and go to page six this will get me the following:

51-60/100
  *   *
  |   |--------- Total records
  | 
  |-------- Displayed range of records

If change the page items per page to 25 it will be set to 51-75/100 . But if I set it back to 10 it will display me 71-80 .

It somehow feels like a weird behaviour, and I am sure, that the calculation that I came up with is faulty. I would think, that the right result should be 51-60 -> (set to 25 per Page) -> 51-75 -> (set to 10 per Page) -> 51-60

Here is my code:

itemsPerPageChanged(newItemsPerPage) {
    // On every change of the items per page the total amount of pages changes
    this.totalPages = Math.ceil(this.totalItems / newItemsPerPage);

    // Here I calculate the current page depending on the itemsPerPage size
    this.page = Math.ceil((this.itemsPerPage * this.page) / newItemsPerPage);

    // If the current page is bigger than total possible pages the ceil went to far and we take the last possible page as current page
    if (this.page > this.totalPages) this.page = this.totalPages;

    this.itemsPerPage = newItemsPerPage;
    this.getItems();
},

What is the right formula? I just can't get my head around it right now. :(

If you have first page's number 1, you should calculate page in the following way:

const pageFirstItemIndex = this.itemsPerPage * (this.page - 1) + 1;
this.page = Math.ceil(pageFirstItemIndex / newItemsPerPage);

and

displayedRangeOfRecords = `${itemsPerPage * (page - 1) + 1}-${itemsPerPage * page}`;

I tried your code sample and it works for me, if

displayedRangeOfRecords = `${this.itemsPerPage * this.page + 1}-${this.itemsPerPage * (this.page + 1)}`;

PS L=10 and P=5 maps to L=25 and P=2 (not P=3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM