how to get and set the current page number in primeNG datatable?
Asked Answered
T

3

8

I am using primeNG datatable in my angular project. In one of my scenario I need to get the current page number of primeNG data table and pass that number to the next screen and when user navigate back to previous screen I want to set that page number again.

I checked the primeNG datatable but there is no clear way to get and set the current page number.

Tetragon answered 24/8, 2017 at 8:28 Comment(0)
M
14

Well you can't get page number directly, but you can get offset (zero based) of first displayed row and then knowing number of items displayed per page calculate page number.

From documentation:
"...Paginator can also be controlled via model using a binding to the first property where changes trigger a pagination. Optionaly this property supports two-way binding so that model value can be updated on pagination as well. Here is an example to reset the paginator externally.",

"...first - Zero-relative number of the first row to be displayed. ", (https://www.primefaces.org/primeng/#/datatable, https://www.primefaces.org/primeng/#/paginator)

template:

<p-dataTable [value]="cars" [rows]="10" [paginator]="true" [(first)]="first">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

<button type="button" (click)="reset()" label="Reset"></button>

code:

export class DataTableDemo implements OnInit {

    cars: Car[];

    first: number = 0;

    constructor(private carService: CarService) { }

    ngOnInit() {
        this.carService.getCarsSmall().then(cars => this.cars = cars);
    }

    reset() {
        this.first = 0;
    }
}

As documentation states, by binding [(first)] to variable in your component you also get your variable updated when pagination state changes, so you can calculate page number like this pageNumber = offset/itemsPerPage

Mucoviscidosis answered 28/8, 2017 at 6:50 Comment(3)
Did it work for you ? because on my page first is not able to do anything !Keeley
Calculating the first row number of the last page is a nightmare since the page size (itemsPerPage) is also a variable because of [rowsPerPageOptions]="[10, 50, 100]"Exigent
@SackySan Do you have a better solution using api-s that existed when this question was asked 3 years ago? If yes, why not post is as answerMucoviscidosis
G
3

use <p-paginator> this label has a function called onPageChange() . you can get page number in this function

Gnash answered 3/9, 2018 at 15:35 Comment(0)
B
1

use [lazy]="true" (onLazyLoad)="loadCustomers($event)

{first}

divide the first with number of items you are displaying in your code you will get the page number

Buccal answered 23/4, 2021 at 5:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.