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.

zennith
  • 410
  • 2
  • 5
  • 17

1 Answers1

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.
TimeTraveler
  • 1,223
  • 12
  • 15
  • Thanks. With [(first)] we are able to control the pagination but the data on the datatable still remains the same. – zennith Jun 28 '17 at 09:49
  • @zennith i have modified answer with work around, there is a defect raised with documented way of doing same. – TimeTraveler Jun 29 '17 at 07:16