Angular

Angular 15 Pagination with NGX Pagination Example

Pinterest LinkedIn Tumblr

In Angular 15, pagination can be achieved by using a third-party library such as NGX Pagination. NGX Pagination is a simple and customizable pagination component that can be easily integrated into an Angular 15 application.

Here’s an example of how you might use the NGX Pagination component to paginate an array of data in an Angular 15 application:

First, you need to install the package using npm or yarn,

Copy codenpm install ngx-pagination

or

Copy codeyarn add ngx-pagination

Then in your component, you can import the pagination module and add it to the imports array in the @NgModule decorator,

Copy codeimport { NgxPaginationModule } from 'ngx-pagination';

@NgModule({
  imports: [
    NgxPaginationModule
  ],
  // ...
})
export class AppModule { }

Then in your component.html, you can use the pagination component to paginate an array of data

Copy code<div *ngFor="let item of data | paginate: { itemsPerPage: 10, currentPage: p }">
  {{ item }}
</div>

<pagination-controls (pageChange)="p = $event"></pagination-controls>

In this example, the data array is passed through the paginate pipe, which takes in an options object with the itemsPerPage and currentPage properties. The pagination-controls component is used to display the pagination controls and the (pageChange) event is used to update the p variable, which is used to update the current page displayed.

You can also customize the pagination controls and items per page, by using the pagination-template directive,

Copy code<pagination-template #p="paginationApi" (pageChange)="p = $event">
  <div class="custom-pagination">
    <button class="prev-btn" [disabled]="p.isFirstPage()" (click)="p.previous()">Previous</button>
    <span class="current-page">{{p.getCurrent()}}</span>
    <button class="next-btn" [disabled]="p.isLastPage()" (click)="p.next()">Next</button>
  </div>
</pagination-template>

This way you can customize the look and feel of the pagination controls.

NGX Pagination provides many options and directives to customize the pagination according to your need. It’s a flexible pagination library that can be easily integrated into an Angular 15 application, this is just a basic example of how it can be used.

Write A Comment