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.
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