September 5, 2022 08:41 by
Peter
Angular ngx-pagination Sample Implementation Step By Step Guide
In this example, I will show you how to implement ngx-pagination in your Angular Application.
ngx-pagination is the simplest pagination solution in Angular.
ngx-pagination also offers flexibility, responsiveness, and very handy customization.
I assumed that you have already installed Angular on your local machine. If not then here’s the link to basic Angular Installation.
FYI: I’m a newbie in Angular I’m just enjoying documenting my journey in learning it.
Step 1: Create Angular Project
Create a new project called ngx-pagination-sample
ng new ngx-paging-sample
Answer the 2 Angular CLI Questions:
Would you like to add Angular routing? No
Which stylesheet format whould you line to use? CSS
After installation, Navigate inside the project folder and open the application.
In my case, I Created a folder in drive: C called Angular and created the ngx-pagination-sample allication inside of it.
C:\Angular>cd ngx-pagination-sample
C:\Angular\ngx-paging-sample>code .
Step 2: Install ngx-pagination
Open Git Bash on your VS Code Terminal, Excecute the following command to add ngx-pagination
ng add ngx-pagination
OR
npm install ngx-pagination
The difference between ng add and npm install ng add, to look for the compatible version to install for your Angular Application while npm install installs the latest version of ngx-pagination which sometimes there are some incompatibility issues especially if you’re using an older version of Angular.
If you’re using latest Angular Version then use npm install.
Step 3: Install Bootstrap for table and styles
We need to install the Bootstrap UI package for styling the table and pagination.
Execute the following command:
npm install bootstrap
Go to the angular.json file and look for styles then add the following:
"./node_modules/bootstrap/dist/css/bootstrap.min.css"
Step 4: Setting up Data Model, Service, and Temporary Data
Go to app.module.ts and Import HttClientModule.
This module will help the service to fetch data from a third-party server but in our case, we’re going to use json file for our temporary data.
import { HttpClientModule } from ‘@angular/common/http’;
@NgModule({
declarations: […],
imports: [
HttpClientModule
],
bootstrap: […]
})
export class AppModule {}
Download Temporary Data customers.json then paste it inside your application assets folder.
Create a folder called _models
Inside of _models folder create an interface model called customer.model.ts
export interface Customer {
id: number;
firstName: string;
lastName: string;
birthday: Date;
mobileNumber: string;
email: string;
createdOn: Date;
}
Inside of _models folder create an interface model called paging-config.model.ts
export interface PagingConfig {
currentPage: number;
itemsPerPage: number;
totalItems: number;
}
Create a folder called _service and inside of it generate a data service called customer, you may create the service manually or type the following:
ng generate service customer
OR
ng g s customer
Add the code in customer.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Customer } from '../_models/customer.model';
@Injectable({
providedIn: 'root'
})
export class CustomerService {
constructor(private httpClient: HttpClient) {}
getCustomers(): Observable < Customer[] > {
return this.httpClient.get < Customer[] > ("assets/customers.json");
}
}
Step 5: Setting up Angular ngx-pagination
Implement PagingConfig on your AppComponent.ts and add initial values on the properties that will be implemented.
Code in the app.component.ts
import { Component } from '@angular/core';
import { Customer } from './_models/customer.model';
import { PagingConfig } from './_models/paging-config.model';
import { CustomerService } from './_services/customer.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements PagingConfig {
title = 'ngx-paging-sample';
currentPage:number = 1;
itemsPerPage: number = 5;
totalItems: number = 0;
tableSize: number[] = [5, 10, 15, 20];
customers = new Array<Customer>();
pagingConfig: PagingConfig = {} as PagingConfig;
constructor(private customerService: CustomerService){
this.getCustomers();
this.pagingConfig = {
itemsPerPage: this.itemsPerPage,
currentPage: this.currentPage,
totalItems: this.totalItems
}
}
getCustomers(){
this.customerService.getCustomers()
.subscribe(res=> {
this.customers = res;
this.pagingConfig.totalItems = res.length;
});
}
onTableDataChange(event:any){
this.pagingConfig.currentPage = event;
this.getCustomers();
}
onTableSizeChange(event:any): void {
this.pagingConfig.itemsPerPage = event.target.value;
this.pagingConfig.currentPage = 1;
this.getCustomers();
}
}
pagingConfig property is used for ngx-pagination paginate configuration.
pagingConfig property will be instantiated inside the AppComponent constructor.
Add the HTML code on your app.component.html
<div class="container">
<div class="row justify-content-between">
<div class="col-4">
<h5 class="h3">NGX Pagination</h5>
</div>
<div class="col-2">
<div class="row g-3 align-items-center">
<div class="col-auto">
<label class="control-label" for="noOfRows">No. of Rows</label>
</div>
<div class="col-auto">
<select name="noOfRows" (change)="onTableSizeChange($event)" class="form-select form-select-sm">
<option *ngFor="let size of tableSize" [ngValue]="size">
{{ size }}
</option>
</select>
</div>
</div>
</div>
</div>
<br>
<table class="table table-bordered">
<thead class="table-dark">
<tr>
<th>Id</th>
<th>Firt Name</th>
<th>Last Name</th>
<th>Birth Date</th>
<th>Mobile Number</th>
<th>Email</th>
<th>Registration Date</th>
</tr>
</thead>
<tr *ngFor="let customer of customers | paginate : pagingConfig; let i = index">
<td>{{ customer.id }}</td>
<td>{{ customer.firstName }}</td>
<td>{{ customer.lastName }}</td>
<td>{{ customer.birthday | date : 'MMMM dd,yyyy' }}</td>
<td>{{ customer.mobileNumber }}</td>
<td>{{ customer.email }}</td>
<td>{{ customer.createdOn | date : 'MM/dd/yyyy' }}</td>
</tr>
</table>
<div class="d-flex justify-content-center">
<pagination-controls
previousLabel="Prev"
nextLabel="Next"
(pageChange)="onTableDataChange($event)">
</pagination-controls>
</div>
</div>
Run the application,
ng serve -o