7

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.

user3340357
  • 101
  • 1
  • 2
  • 6

3 Answers3

11

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

gio
  • 337
  • 3
  • 8
  • 2
    Did it work for you ? because on my page first is not able to do anything ! – heman123 Mar 26 '18 at 11:58
  • 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]"` – Sacky San Jan 21 '20 at 00:08
  • @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 answer – gio Jan 23 '20 at 07:00
3

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

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
C.Rookie
  • 31
  • 4
0

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