简体   繁体   中英

PrimeNG Paginator set Page

I'm using the primeng paginator component inside an Angular 9 Project to page a huge list of profiles. If a user is on page 3, opens a profile and returns to search, the current page is 1, but it should be 3. I have saved the page inside a service, so the right data is shown, but the paginator is showing the wrong page. I could not find a way to set the current page of the paginator. Using the [first] attribute is not working.

You need to set the page manually. You can use Angular @ViewChild decorator to get access to PrimeNg Paginator component.

Give an id to that paginator in template:

<p-paginator #paginator ...></p-paginator>

And use it in component:

import { Paginator } from 'primeng/paginator';


@ViewChild('paginator', { static: true }) paginator: Paginator

private updateCurrentPage(currentPage: number): void {
  setTimeout(() => this.paginator.changePage(currentPage));
}

The first property is the best option to define the current page of the pager provided by the Primeng.

first = (page-1) * rows;

In template,

      <p-paginator
        [rows]="10"
        [totalRecords]="120"
        [rowsPerPageOptions]="[10, 20, 30]"
        [first]="first"
      ></p-paginator>

In component,

    pageSize = 10;  
    currentpage = 2;
    first;
    
     ngOnInit() {     
        this.first =  (this.currentpage-1)* this.pageSize;
     }

It will successfully set the active page without using setTimeout.

If you have a listing component as a child component then you can keep the value of the Pagination event.first in the parent component and pass it back to the child component something like this.

@Input() paginationFirstValue: number = 0;
<p-paginator
      #paginator
      [first]="paginationFirstValue"
      [rows]="10"
      selectionMode="single"
      [alwaysShow]="false"
      [totalRecords]="dataObj.total"
      (onPageChange)="paginate($event)"
    ></p-paginator>

And emit the event to the parent

paginate(event: Pagination): void {
this.paginationFirstValue = event.first;
this.pageChange.next(event);

}

The paginator current page is managed using the first property. First property must contain the index of the first row displayed. You can automate this using the Event.first from the event handler: onPageChange($event)

Solution: In view, create a paginator:

<p-paginator [rows]="paginatorPageSize" [totalRecords]="paginatorTotalRecords" (onPageChange)="paginate($event)"
             [first]="paginatorFirstRecordIndex"></p-paginator>

// controller change

 paginate($event) {
  ...
    this.paginatorFirstRecordIndex=$event.first

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM