Angular 9|8 Pagination Example using ngx-pagination in Tables

In this post, we’ll discuss how to add pagination on tabular or datatable in Angular application without using a library or framework. The ngx-pagination package module provides a component directive to quickly add pagination with a table using custom template and design.

The ngx-pagination provides highly customized pagination solution it is fully responsive and can adjust its position according to screen size. It is packed with good looking themes and we’ll also get to know how we can customize using own styling.

We’ll create a new Angular project in latest version 9.x.x but this package is compatible with all previous major version like Angular 5,6,7 & 8.

Let’s begin with Implementation

 

# Update Angular CLI

Make sure to update your Angular CLI tool by running below npm command in your terminal window. You can go ahead with your current version as well

$ npm install -g @angular/cli

 

# Create an Angular project

Now, we'll create a new Angular project using the Angular CLI by running below ng command

$ ng new ngx-pagination-tutorial
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? CSS

move to project directory

$ cd ngx-pagination-tutorial

if you have Visual Studio Code install, hit below command to open the project

$ code .

 

# Install ngx-pagination Package

After creating the Angular project, now we'll install the ngx-pagination package. Run following npm command in the terminal window

$ npm install ngx-pagination --save

 

# Import Pagination Module

Now, we'll import the NgxPaginationModule provided by ngx-pagination in the Application. In our project we'll open the app.module.ts file then import this module as shown below:

// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { NgxPaginationModule } from 'ngx-pagination';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,

    NgxPaginationModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

# Basic Table Styling

In this tutorial, we'll create a simple Table to add the pagination. To make Table look good, include the bootstrap.css in the index.html file's head section

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

 

# Adding Pagination

First, to keep it simple we will implement the quickest and basic pagination with least configurations.

Implement Pagination in Component. Open app.component.html and add the following code

paginate: This filter is having data related configurations with these options available.

<div style="text-align:center">
  <h4>
    Basic Pagination
  </h4>

  <table class="table">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">Item</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of collection.data | paginate: config">
        <th scope="row">{{item.id}}</th>
        <td>{{item.value}}</td>
      </tr>
    </tbody>
  </table>

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

</div>

 

In the app.component.ts file replace below code

pageChanged: This is passing the current page to the configuration.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  config: any;
  collection = { count: 60, data: [] };

  constructor() {

    //Create dummy data
    for (var i = 0; i < this.collection.count; i++) {
      this.collection.data.push(
        {
          id: i + 1,
          value: "items number " + (i + 1)
        }
      );
    }

    this.config = {
      itemsPerPage: 5,
      currentPage: 1,
      totalItems: this.collection.count
    };
  }

  pageChanged(event){
    this.config.currentPage = event;
  }

}

That's it! your Pagination is ready for users to play 🙂

 

Customized Elements of Pagination

We can customize various elements in pagination. There is also an option to make it responsive, change navigation labels, maxSize option to keep visible numbers.
<!-- app.component.html -->
<div style="text-align:center">
  <h4>
    Customized Elements of Pagination
  </h4>

  <table class="table">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">Item</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of collection.data | paginate: config">
        <th scope="row">{{item.id}}</th>
        <td>{{item.value}}</td>
      </tr>
    </tbody>
  </table>

  <pagination-controls 
                         [maxSize]="maxSize"
                         [directionLinks]="directionLinks"
                         [autoHide]="autoHide"
                         [responsive]="responsive"
                         [previousLabel]="labels.previousLabel"
                         [nextLabel]="labels.nextLabel"
                         [screenReaderPaginationLabel]="labels.screenReaderPaginationLabel"
                         [screenReaderPageLabel]="labels.screenReaderPageLabel"
                         [screenReaderCurrentLabel]="labels.screenReaderCurrentLabel"
                         (pageChange)="onPageChange($event)"></pagination-controls>

</div>


// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  collection = { count: 60, data: [] };
  config = {
    itemsPerPage: 5,
    currentPage: 1,
    totalItems: this.collection.count
  };

  public maxSize: number = 7;
  public directionLinks: boolean = true;
  public autoHide: boolean = false;
  public responsive: boolean = true;
  public labels: any = {
      previousLabel: '<--',
      nextLabel: '-->',
      screenReaderPaginationLabel: 'Pagination',
      screenReaderPageLabel: 'page',
      screenReaderCurrentLabel: `You're on page`
  };
  constructor() {
    //Create dummy data
    for (var i = 0; i < this.collection.count; i++) {
      this.collection.data.push(
        {
          id: i + 1,
          value: "items number " + (i + 1)
        }
      );
    }
  }
  onPageChange(event){
    console.log(event);
    this.config.currentPage = event;
  }

}

Use Custome Template in Pagination

To customize the UI of pagination we need to use the pagination-template directive as follows

<!-- app.component.html -->
<div style="text-align:center">
  <h4>
    Use Custome Template in Pagination
  </h4>

  <table class="table">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">Item</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of collection.data | paginate: config">
        <th scope="row">{{item.id}}</th>
        <td>{{item.value}}</td>
      </tr>
    </tbody>
  </table>

  <pagination-template #p="paginationApi" [id]="config.id" (pageChange)="config.currentPage = $event">


    <div class="custom-pagination">
      <div class="pagination-previous" [class.disabled]="p.isFirstPage()">
        <span *ngIf="!p.isFirstPage()" (click)="p.previous()">
          < 
            </span> 
        </div> 
        <div class="page-number" *ngFor="let page of p.pages" [class.current]="p.getCurrent() === page.value">
              <span (click)="p.setCurrent(page.value)" *ngIf="p.getCurrent() !== page.value">{{ page.label }}</span>
            <div *ngIf="p.getCurrent() === page.value">
              <span>{{ page.label }}</span>
            </div>
        </div>
        <div class="pagination-next" [class.disabled]="p.isLastPage()">
          <span *ngIf="!p.isLastPage()" (click)="p.next()"> > </span>
        </div>
    </div>

  </pagination-template>

</div>
// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  collection = { count: 60, data: [] };
  config = {
    id: 'custom',
    itemsPerPage: 5,
    currentPage: 1,
    totalItems: this.collection.count
  };

  public maxSize: number = 7;
  public directionLinks: boolean = true;
  public autoHide: boolean = false;
  public responsive: boolean = true;
  public labels: any = {
      previousLabel: '<--',
      nextLabel: '-->',
      screenReaderPaginationLabel: 'Pagination',
      screenReaderPageLabel: 'page',
      screenReaderCurrentLabel: `You're on page`
  };

  constructor() {

    //Create dummy data
    for (var i = 0; i < this.collection.count; i++) {
      this.collection.data.push(
        {
          id: i + 1,
          value: "items number " + (i + 1)
        }
      );
    }

  }

  onPageChange(event){
    console.log(event);
    this.config.currentPage = event;
  }

}

Use the following CSS in the app.component.css file

.custom-pagination .page-number{
    display: inline-block;
    /* padding: 5px 12px; */
    background: #afffe6;
    margin: 0px 4px;
    border-radius: 25px;
}

.page-number.current{
    background: #ffffff!important;
    border: 2px solid #458873;
}

.page-number span{
    display: block;
    width: 28px;
    height: 28px;
    font-size: 18px;
    cursor: pointer;
}

.pagination-previous,.pagination-next{
    display: inline-block;
    font-weight: bold;
}

 

By following above few steps you can easily add fully customizable pagination in your data listings very quickly.

Conclusion: The ngx-pagination package provides a quick solution to add pagination in Tables or listings without any need of third-party frameworks like Bootstrap or Material. This package provides good customization and also responsive behaviour.

 

 

 

 

Subscribe
Notify of
4 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Works great. The custom gave an issue about ID not registered but the simple example is terrific.

thanks, this article help me..