Simple pagination using primeNG

PrimeNG is a popular UI component library for Angular, and it includes several pagination components that you can use to implement basic pagination in your Angular application. Here’s a basic example of how to use the p-paginator component from PrimeNG:

  1. First, you’ll need to install PrimeNG and its dependencies. You can do this using npm:
npm install primeng primeicons --save
  1. Next, you’ll need to import the PaginatorModule in your app.module.ts file:
import { PaginatorModule } from 'primeng/paginator';
...
@NgModule({
  imports: [
    ...
    PaginatorModule,
    ...
  ],
  ...
})
export class AppModule { }
  1. Now, you can use the p-paginator component in your component template. Here’s an example template that shows how to use the p-paginator component to paginate a list of items:
<div *ngFor="let item of itemsToShow">
  {{ item }}
</div>

<p-paginator [totalRecords]="totalItems" [rows]="itemsPerPage" [(page)]="currentPage"></p-paginator>

In this example, itemsToShow is an array of items that you want to display in your list. totalItems is the total number of items in your array, and itemsPerPage is the number of items to display per page. currentPage is a variable that you can bind to in order to keep track of the current page.

  1. Finally, you’ll need to update the itemsToShow array based on the current page and the number of items per page. You can do this by adding a method to your component that uses the slice method to extract a subset of the array based on the current page and the number of items per page. Here’s an example method that you can use:
updateItemsToShow() {
  const startIndex = this.currentPage * this.itemsPerPage;
  const endIndex = startIndex + this.itemsPerPage;
  this.itemsToShow = this.items.slice(startIndex, endIndex);
}

In this method, items is the original array of items that you want to paginate. The startIndex and endIndex variables are calculated based on the current page and the number of items per page. The slice method is then used to extract the subset of items to display on the current page.

You’ll also need to call this method whenever the currentPage or itemsPerPage variables change. You can do this using the ngOnChanges lifecycle hook:

ngOnChanges() {
  this.updateItemsToShow();
}

That’s it! With these steps, you should have a basic pagination component in your Angular application using PrimeNG’s p-paginator component.