Angular 10 Pagination Tutorial with ngx-pagination Example

Last updated on by Digamber

This is a comprehensive Angular 10 Pagination tutorial. In this tutorial, we will learn how to add server-side pagination in the Angular 10 data table. To add pagination in Angular, we will use the ngx-pagination package.

We will also create an angular service to fetch data remotely and display data in tabular form with pagination.

The ngx-pagination offers the simplest yet powerful solution for making pagination in Angular. All hail to its flexibility and responsiveness, customization is pretty handy with ngx-pagination, and yes its is loaded with some beautiful themes too.

Pagination, also known as paging, is the process of dividing a document into discrete pages, either electronic pages or printed pages.
– wikipedia

Create Angular Project

If you don’t have angular cli installed, then run the given below command to install it.

npm install -g @angular/cli

Install a brand new angular application:

ng new angular-pagination-example

Answer few CLI questions:

# ? Would you like to add Angular routing? Yes
# ? Which stylesheet format would you like to use? CSS

Get inside the project root:

cd angular-pagination-example

Install ngx-pagination Module in Angular

Execute the following command to add pagination in angular, and we need to install the ngx-pagination library.

npm install ngx-pagination

Import and Register Pagination Module

Next, we will import the NgxPaginationModule in the angular app’s main AppModule.

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 { }

Style Table with Bootstrap

We need to install the Bootstrap UI package for styling the table and pagination UI components.

npm install bootstrap

Register Bootstrap CSS path in styles array within angular.json file.

"styles": [
     "node_modules/bootstrap/dist/css/bootstrap.min.css",
     "src/styles.css"
]

Setting Up Angular Data Service

We will create post data service in angular; this service file will fetch the data using a custom API or endpoint. With the Angular HTTPClient service’s help, we will make HTTP GET requests and fetch the data from a third-party server.

We need to import the HttpClientModule in app.module.ts to send the HTTP GET request.

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [...],
  imports: [
     HttpClientModule
  ],
  bootstrap: [...]
})

export class AppModule { }

Generate a Data service with the given below command.

ng generate service post

Add code inside the post.service.ts file:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

const endpoint = 'https://jsonplaceholder.typicode.com/posts';

@Injectable({
  providedIn: 'root'
})

export class PostService {

  constructor(private http: HttpClient) { }

  getAllPosts(params): Observable<any> {
    return this.http.get(endpoint, { params });
  }

}

Adding Angular Pagination in Table

Add code in app.component.ts file.

import { Component, OnInit } from '@angular/core';
import { PostService } from './post.service'

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

export class AppComponent implements OnInit {
  POSTS: any;
  page = 1;
  count = 0;
  tableSize = 7;
  tableSizes = [3, 6, 9, 12];

  constructor(private postService: PostService) { }

  ngOnInit(): void {
    this.fetchPosts();
  }  

  fetchPosts(): void {
    this.postService.getAllPosts()
      .subscribe(
        response => {
          this.POSTS = response;
          console.log(response);
        },
        error => {
          console.log(error);
        });
  }

  onTableDataChange(event){
    this.page = event;
    this.fetchPosts();
  }  

  onTableSizeChange(event): void {
    this.tableSize = event.target.value;
    this.page = 1;
    this.fetchPosts();
  }  

}

We have created an Angular 10 pagination component using Bootstrap Table and Pagination UI components.

The *ngFor loop iterate over posts data that we are getting from the Angular post service.abs

Also, passed the paginate: {} object and defined the pagination settings along with the active pagination class.

To display the pagination in angular, we used the pagination-controls directive and bound the onTableDataChange() method with it.

Place code within app.component.html.

<div class="container">
  <h3 class="text-center mt-5 mb-5">
    Angular Basic Pagination Example
  </h3>

  <div class="d-flex flex-row-reverse bd-highlight mb-2">
    <div class="p-2 bd-highlight">
      <select (change)="onTableSizeChange($event)" class="custom-select">
        <option *ngFor="let size of tableSizes" [ngValue]="size">
          {{ size }}
        </option>
      </select>
    </div>
  </div>

  <table class="table">
    <thead>
      <tr>
        <th>ID</th>
        <th>Title</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let post of POSTS | paginate : {
                itemsPerPage: tableSize,
                currentPage: page,
                totalItems: count
              };
        let i = index" [class.active]="i == currentIndex">
        <th scope="row">{{post.id}}</th>
        <td>{{post.title}}</td>
      </tr>
    </tbody>
  </table>

  <div class="d-flex justify-content-center">
    <pagination-controls 
      responsive="true" 
      previousLabel="Prev" 
      nextLabel="Next" 
      (pageChange)="onTableDataChange($event)">
    </pagination-controls>
  </div>

</div>

Start Angular Application

Run the command to start the project:

ng serve --open

Angular 10 Pagination Tutorial with ngx-pagination Example

Eventually, we have created the angular 10 pagination application. We have learned how to customize pagination in angular and implement it with tabular data. I hope you will like this tutorial and share it with others.

You can download the full code example from GitHub.