Site icon RemoteStack

Angular 14 Server-Side Pagination with NGX Pagination Example

Comprehensive Angular pagination tutorial, this step-by-step guide profoundly explains how to create server-side pagination using the third-party ngx-pagination package in Angular application.

Pagination is also recognized by paging, and this is one of the best ways to immaculately divide excessive content into separate pages in a web application.

For implementing pagination in angular can simply be done with the ngx-pagination library.

There are tons of pagination plugins available for Angular in the NPM directory nevertheless the ngx-pagination is best among all.

Whether it is about customization, responsiveness, pre-built pagination themes or styling it gives solution for everything under one roof.

After completing this guide, sequentially, you will be able to create server-side pagination in Angular with HttpClientModule. Hence, let us start building pagination in Angular using the following steps, respectively.

Angular 14 Pagination Example

Install New Angular App

Make sure the Angular CLI tool installed on your system, you can use it to install a new angular app or related packages:

npm install -g @angular/cli

After installing the suggested tool, open the console and initiate the following command to create a new angular app:

ng new angular-pagination-demo

Next, move to the project folder:

cd angular-pagination-example

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, you have to manually disable the strict mode you can set “strict”: false, "noImplicitReturns": false and "strictTemplates": false inside the compilerOptions and angularCompilerOptions in tsconfig.json file.

Install Bootstrap Package

Further, from your console, run the command to install the Bootstrap package:

npm i bootstrap

Plus, add the Bootstrap CSS in angular.json file inside the styles property:

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

It will allow you to style the table component without writing additional styling code:

Install NGX Pagination Library

Next, install the ngx-pagination package with the help of the provided command:

npm i ngx-pagination

You can also check out the useful set of features of ngx pagination API here.

Register NgxPaginationModule in App Module

Additionally, import NgxPaginationModule from ‘ngx-pagination’ package likewise insert inside the imports array as suggested;

...
...

import { NgxPaginationModule } from 'ngx-pagination';

@NgModule({
  ...
  imports: [
    ...
    ...
    NgxPaginationModule
  ],
  ...
  ...
})

export class AppModule { }

Import HttpClientModule

Open app.module.ts file, plus import HttpClientModule from ‘@angular/common/http’ package, also register inside the imports array:

...
...

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

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

export class AppModule { }

Create Service File

Next, use provided command to create a pagination service file; this will help to make the HTTP request with REST API to get the data from the server and add it with the pagination:

ng g s pagination

Further, open the pagination.service.ts file plus insert the following code:

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

@Injectable({
  providedIn: 'root'
})

export class PaginationService {

  RESTAPI = 'https://jsonplaceholder.typicode.com/posts';

  constructor(private httpClient: HttpClient) { }

  fetchPosts(): Observable<any> {
    return this.httpClient.get(this.RESTAPI);
  }

}

Implement Server Side Pagination in Angular

In this step, you have to open the app.component.ts file plus replace the current code with the following code:

import { Component, OnInit } from '@angular/core';
import { PaginationService } from './pagination.service'

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

export class AppComponent implements OnInit {
  Articles: any;
  page = 1;
  count = 0;
  tableSize = 8;
  tableSizesArr = [4, 8, 12];

  constructor(private paginationService: PaginationService) { }

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

  showData(): void {
    this.paginationService.fetchPosts()
      .subscribe(
        res => {
          this.Articles = res;
          console.log(res);
        },
        err => {
          console.log(err);
        });
  }

  tabSize(event){
    this.page = event;
    this.showData();
  }  

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

}

Next, open app.component.html file and add the following code:

<div class="container">

  <div>
    <div class="p-2 bd-highlight">
      <select (change)="tableData($event)" class="custom-select">
        <option *ngFor="let size of tableSizesArr" [ngValue]="size">
          {{ size }}
        </option>
      </select>
    </div>
  </div>

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

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

</div>

Run Angular Project

You have to start the angular development server, hence execute the following command from the console:

ng serve

Add this url on the browser to test the applicaiton:

http://localhost:4200

Conclusion

Pagination is a better way to arrange the content and display data categorically.

In this tutorial, we created simple pagination and render the data from the server and bind it to pagination using the ngx pagination package i hope you will like this tutorial.

Exit mobile version