,

Server Side Pagination in Angular 14 using NGX Pagination

In server-side-based pagination, we fetch remote data via REST API and populate it in real-time in tabular form or any list items. In this guide, you will learn how to easily implement server-side pagination in Angular applications in a few steps. Pagination is the way of dividing a huge set of data records into multiple…

By.

•

min read

In server-side-based pagination, we fetch remote data via REST API and populate it in real-time in tabular form or any list items. In this guide, you will learn how to easily implement server-side pagination in Angular applications in a few steps.

Pagination is the way of dividing a huge set of data records into multiple pages so that a user can view only a relevant set of records on a specific page. Navigation is very handy using Next, Previous or page number making it a user-friendly choice.

By implementing pagination, we can optimize the application performance to large extent, as in server-side pagination only the request page records are downloaded from a remote server. Moreover, these records can be easily sorted or can be searched for a specific term to filter out further.

We will implement server-side pagination Angular table using the NGX Pagination, which supports a number of configurations and even handles to match app behaviour requirements.

How to Add Server-Side Pagination in Angular App?

Follow these quick steps to implement pagination on nearly anything including cards, lists, table simple div elements etc.

Step 1 – Create Angular Application

Step 2 – Add Bootstrap (Optional)

Step 3 – Install NGX Pagination Package

Step 4 – Import NGX Pagination Module

Step 5 – Implement Server-Side Pagination

Step 6 – Create Table and Pagination Component

Step 7 – See In Action

 

Create Angular Application

Before you create an Angular app, make sure you have installed the latest version of NG CLI on your system:

npm install -g @angular/cli

 

Create a new angular app by executing below ng command by providing name:

ng new angular-pagination-app

 

Enter inside the application folder:

cd angular-pagination-app

 

Add Bootstrap (Optional)

To quickly style the application we will add Bootstrap by executing the below npm command to install bootstrap styles.

npm install bootstrap

 

Afterwards, you need to include the bootstrap.css file inside the angular.json file under the styles array as pointed below:

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

 

Install NGX Pagination Package

Going forward, install the important prerequisite library named NGX Pagination by executing the below command in the terminal window:

npm install ngx-pagination

 

Import NGX Pagination Module

Now, update the app.module.ts file to import a few of the required modules to implement server-side pagination.

We will import the NgxPaginationModule to create and add the Pagination component, with that, we also need the HttpClientModule to make remote HTTP calls to fetch server-side data.

The AppModule will look like this after importing the module:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

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

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule, 
    HttpClientModule, 
    NgxPaginationModule
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

 

Implement Server-Side Pagination

We will update the App Component to add a function to call the remote JSON data via the HTTP get method. To test we used the OMDB test API.

The getMovies() function will fetch remote data based on the page number passed in the GET URL. On getting the response the totalMovies and Movies get updated.

Update the app.component.ts file with following code:

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  private url = 'https://www.omdbapi.com/?apikey=e8067b53&s=car';
  Movies: any;
  totalMovies!: number;
  pageNumber: number = 1;
  constructor(private httpClient: HttpClient) {}
  ngOnInit() {
    this.getMovies();
  }
  getMovies() {
    this.httpClient
      .get(this.url + '&page=' + this.pageNumber)
      .subscribe((res: any) => {
        this.Movies = res.Search;
        this.totalMovies = res.totalResults;
      });
  }
  changePage(event: number) {
    this.pageNumber = event;
    this.getMovies();
  }
}

 

Create Table and Pagination Component

Now we will add a table to iterate the rows we got from the HTTP response for the selected page. Under beneath we will create the pagination by adding the <pagination-controls> component.

Open the app.component.html file and update it with the following template HTML:

<div class="container">
  <h1>Server-Side Pagination in Angular</h1>
  <div>
    <table class="table">
      <thead>
        <tr>
          <th scope="col">Title</th>
          <th scope="col">Type</th>
          <th scope="col">Year</th>
          <th scope="col">Poster</th>
        </tr>
      </thead>
      <tbody>
        <tr
          *ngFor="
            let movie of Movies
              | paginate
                : {
                    itemsPerPage: 6,
                    currentPage: pageNumber,
                    totalItems: totalMovies
                  }
          "
        >
          <td scope="row">{{ movie.Title }}</td>
          <td>{{ movie.Type }}</td>
          <td>{{ movie.Year }}</td>
          <td>
            <img height="30" src="{{ movie.Poster }}" alt="{{ movie.Title }}" />
          </td>
        </tr>
      </tbody>
    </table>
    <div class="d-flex justify-content-center">
      <pagination-controls
        (pageChange)="changePage($event)"
      ></pagination-controls>
    </div>
  </div>
</div>

 

See In Action

We are done with the implementation, now you can execute the following command to start the development server and run your app:

npm start

You can open this URL and see your app working:

http://localhost:4200/

 

Conclusion

We discussed how to easily implement server-side pagination in the Angular table using the NGX Pagination library. Using a GET call HTTP request we fetched pages for a particular offset page number and populate the table UI. Using this useful library, we can implement pagination behaviour on any type of UI elements like li lists, cards or simple div etc. Moreover, you can easily customise the CSS style of pagination. More details can be found here.

 

Leave a Reply

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