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…

By.

•

min read

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</pre>
 
<h3># Create an Angular project</h3>
Now, we'll create a new Angular project using the Angular CLI by running below ng command
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ ng new ngx-pagination-tutorial
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? CSS</pre>
move to project directory
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ cd ngx-pagination-tutorial</pre>
if you have Visual Studio Code install, hit below command to open the project
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ code .</pre>
 
<h3># Install <code>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</pre>
 
<h3># Import Pagination Module</h3>
Now, we'll import the <code>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"></pre>
 
<h3># Adding Pagination</h3>
First, to keep it simple we will implement the quickest and basic pagination with least configurations.

Implement Pagination in Component. Open <strong>app.component.html</strong> and add the following code

<code><strong>paginate</strong>: 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></pre>
 

In the <strong>app.component.ts</strong> file replace below code
<div>
<div><code><strong>pageChanged</strong>
: 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;
}

}</pre>
<a href="http://www.freakyjolly.com/wp-content/uploads/2019/03/angular-pagination-example.gif"><img class="aligncenter size-full wp-image-2266" src="http://www.freakyjolly.com/wp-content/uploads/2019/03/angular-pagination-example.gif" alt="" width="483" height="402" /></a>

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

 
<div>
<h3>Customized Elements of Pagination</h3>
</div>
<div></div>
<div>We can customize various elements in pagination. There is also an option to make it responsive, change navigation labels, <code><strong>maxSize</strong>
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>

</pre>
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">// 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;
}

}
</pre>
<a href="http://www.freakyjolly.com/wp-content/uploads/2019/03/angular-pagination-example2.gif"><img class="aligncenter size-full wp-image-2269" src="http://www.freakyjolly.com/wp-content/uploads/2019/03/angular-pagination-example2.gif" alt="" width="453" height="332" /></a>

</div>
<h3>Use Custome Template in Pagination</h3>
To customize the UI of pagination we need to use the <strong><code>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></pre>
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">// 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;
}

}
</pre>
Use the following <strong>CSS </strong>in the <strong>app.component.css</strong> file
<pre><code class="language-scss">.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;
}</pre>
 
<div>By following above few steps you can easily add fully customizable pagination in your data listings very quickly.</div>
<div></div>
<strong>Conclusion</strong>: The <code>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.

 

 

 

 

4 responses to “Angular 9|8 Pagination Example using ngx-pagination in Tables”

  1. papi Avatar
    papi

    •

    It’s just amazing. In fact, that was what I wanted
    Great, thanks you.

  2. Roy Avatar
    Roy

    •

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

    1. Juancar Avatar
      Juancar

      •

      What issue and how can I fix it?

  3. dann Avatar
    dann

    •

    thanks, this article help me..

Leave a Reply

Your email address will not be published. Required fields are marked *