Get current page and move to specific page in NgPrime datatable
Asked Answered
M

1

6

I am using datatable from primefaces - primeNg. Can I get the current page I am in and set the datatable to particular page programatically?

I saw that datatable uses pagination component within, but how to access it using @ViewChild? Any help will be appreciated.

Maximilianus answered 27/6, 2017 at 6:3 Comment(0)
E
12
<p-dataTable #dt [value]="items" [rows]="10" [paginator]="true" [(first)]="first"  (onPage)="paginate($event)">

Work Around - To set the datatable to particular page programatically.

@ViewChild('dt') dataTable: DataTable;

setCurrentPage(n: number) {
    let paging = {
    first: ((n - 1) * this.dataTable.rows),
    rows: this.dataTable.rows
};
this.dataTable.paginate(paging);
}
// this.setCurrentpage(pageNumber) will set table to given page number

To get the current page you are at, use (onPage) event like this

paginate(event) {
//event.first: Index of first record being displayed 
//event.rows: Number of rows to display in new page 
//event.page: Index of the new page 
//event.pageCount: Total number of pages 
let pageIndex = event.first/event.rows + 1 // Index of the new page if event.page not defined.
}

There seems to be a defect raised for below way of setting page number, so you may need to use work around until defect is closed. As per primeng documentation To set the datatable to particular page programatically please set 'first' with the row number you want to see. for example

this.first = 10 //will show second page, OR
this.first=20  //will show third page.
Encephaloma answered 28/6, 2017 at 8:54 Comment(2)
Thanks. With [(first)] we are able to control the pagination but the data on the datatable still remains the same.Maximilianus
@Maximilianus i have modified answer with work around, there is a defect raised with documented way of doing same.Encephaloma

© 2022 - 2024 — McMap. All rights reserved.