Site Admin
Site Admin Founder of MeaningArticles
3173 Views

Angular 12 Pagination with NGX Pagination

Hello Dev.

this is a comprehensive Angular 12 Pagination article. on this article, we are able to learn how to add server-side pagination inside the Angular 12 data table. to feature pagination in Angular, we can use the ngx-pagination package.

we will also create an angular service to fetch data remotely and show records in tabular form with pagination.

the ngx-pagination offers the only yet effective answer 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 lovely themes too.


Step 1: 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 new angular application using below command:

ng new angular-pagination-example

Get inside the project root:

cd angular-pagination-example


Step 2: Install ngx-pagination Module

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

npm install ngx-pagination


Step 3: 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 { }


Step 4: 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
angular.json

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


Step 5: Setting Up 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 assist, we can 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.
app.module.ts

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:
post.service.ts

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 });
  }

}


Step 6: Add Pagination in Table

Add below code in app.component.ts file.
app.component.ts

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 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.
app.component.html

<div class="container">
  <h3 class="text-center mt-5 mb-5">Angular Basic Pagination Example - meaningarticles.com</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>


Step 7: Start Angular Application

Run the command to start the project:

ng serve --open

finally, we've created the angular 12 pagination application. we've got learned how to personalize pagination in angular and implement it with tabular data.

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.