Angular 16 Pagination with NGX Pagination Tutorial

Last Updated on by in Angular

This is a comprehensive Angular 16 Pagination tutorial. In this tutorial, we will learn how to add server-side pagination in the Angular 16 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

Angular 16 Pagination Example

  • Create Angular Project
  • Install ngx-pagination Module in Angular
  • Import and Register Pagination Module
  • Style Table with Bootstrap
  • Setting Up Angular Data Service
  • Adding Angular Pagination in Table
  • Start Angular Application

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

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 app.module.ts file.

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

import { NgxPaginationModule } from 'ngx-pagination';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, NgxPaginationModule, HttpClientModule],
  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.scss"
]

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(): Observable<any> {
    return this.http.get(endpoint);
  }
}

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.scss'],
})
export class AppComponent implements OnInit {
  POSTS: any;
  page: number = 1;
  count: number = 0;
  tableSize: number = 7;
  tableSizes: any = [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: any) {
    this.page = event;
    this.fetchPosts();
  }

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

We have created an Angular 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>

  <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
        "
      >
        <th scope="row">{{ post.id }}</th>
        <td>{{ post.title }}</td>
      </tr>
    </tbody>
  </table>

  <div class="d-flex justify-content-center">
    <pagination-controls
      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 12 Pagination Tutorial with ngx-pagination Example

Eventually, we have created the angular 12 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.