PageNavigation (Paging) in Angular

In this article, we’ll learn how to display page navigation for data display as a table format in Angular application.
PageNavigation (Paging): It display data in tabular form with pagination. For paging we used “ngx-pagination” plugin for the easily pagination to work.
Let’s create a new project to demo for pagination. For that, you need to run the following command to create a project.


ng new paging-demo

“paging-demo” you need to write your application’s name. Then it will take some time to create the project. After successfully installing that, you need to go to their directory. For example “cd paging-demo”. To Run angular applications, it required to run “ng serve”.
After that, we need to install the “ngx-pagination” npm package in our application. run below command to install.


npm i ngx-pagination

After installing the module we need to add “NgxPaginationModule” in our app.module.ts file. Also we need “HttpClientModule” to get the data from the server side. Display in the below code.


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

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

export class AppModule { }

After import in module we need to create service to get data from the server. To generate service run below command.


npm g s data-service

Fetch data from theserver we currently used “typicode” site. Let’s add below code to fetch data from the server.


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

const endpoint = 'https://jsonplaceholder.typicode.com/posts';

@Injectable()
export class DataServiceService {

  constructor(private http: HttpClient) { }

  getAllPosts(params): Observable {
    return this.http.get(endpoint, { params });
  }


}



To Draw the page navigation we used the below code to generate paging in our html file where we want.


<pagination-controls 
      previousLabel="Prev" 
      nextLabel="Next" 
      (pageChange)="onTableDataChange($event)">
</pagination-controls>

Let’s create app.component.ts file to get data from the service and draw in table format. display below code.


import { Component, VERSION } from '@angular/core';
import { DataServiceService } from './data-service.service';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  tabledata: any;
  page = 1;
  count = 0;
  tableSize = 10;
  tableSizes = [10, 20, 30, 50];

  constructor(private dataService: DataServiceService) { }

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

  fetchPosts(): void {
    this.dataService.getAllPosts({})
      .subscribe(
        response => {
          this.tabledata = 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();
  }  

}


<div class="container">
  <h3 class="text-center mt-5 mb-5">
    Pagination in Angular
  </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>
        <th>Message</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let post of tabledata | paginate : {
                itemsPerPage: tableSize,
                currentPage: page,
                totalItems: count
              };
        let i = index" >
        <th scope="row">{{post.id}}</th>
        <td>{{post.title}}</td>
        <th>{{post.body}}</th>
      </tr>
    </tbody>
  </table>

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

</div>




Output

Below is the full embeded code for the paging . you can easily used in your application.
Example

Spread the love
  •  
  •  
  •  
  •  
  • 9
  • 2
  •  
  •