When you work with tables or lists, you will withstand a situation at some time where you would need Pagination. Well, in the article we will implement a Server side pagination Angular 2.
Here we will use,
- Angular 2’s Http Module Which I have explained herein-depth, have a look into it.
- Angular 2’s ngFor directive to iterate the data.
- Lastly, ng2-pagination module to render the pagination in our application.
Setting up our Application
Let’s use Angular CLI to setup our application. If you don’t have Angular CLI installed on your machine run the below command to install it globally.npm install -g angular-cli
After Angular CLI installation, to create a new Angular project Run below command. This command will create all the necessary files, download all the required external dependencies and do all of the setup work for us.
ng new AppName
The Application
In this application, I am using NodeJs as a server side language. Basically, We will create rest API to fetch the list of users, in REST HTTP request we will pass the number of the page to fetch the users.
Here I am not storing users data in any database, for this article I will be using a simple array of object which comprises of user’s information. I think Nodejs part is not that much interesting here. so I won’t talk about that.
Let’s talk about Angular 2 and Pagination.
Installing and configuring ng2-pagination module:
In order to use ng2-pagination first, you will need to install it from NPM, run the below command to do the same.
npm i ng2-pagination -S
Above command will download and install the ng2-pagination module and at the same time, save it to package.json
as a dependency.
Now installation is done let’s load this module in our application so, to do that open fileapp.module.ts
and import the ng2-pagination as shown below.
app.module.ts :
/* * Server side pagination Angular 2 * @author Shashank Tiwari */ import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import {Ng2PaginationModule} from 'ng2-pagination'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, HttpModule, Ng2PaginationModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Creating Http service
Let’s first create HTTP service to call the RESTAPI, to create new service in Angular 2 I will use Angular CLI. Use the below command to create a HTTP service,ng generate service http
Now write the below code in your service to call the REST API.
http.service.ts :
/* * Server side pagination Angular 2 * @autthor Shashank Tiwari */ import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; @Injectable() export class HttpService { private BASE_URL:string = 'http://localhost:8080/api/users/'; constructor( private http:Http ) { } public getdata(page:Number):any{ return this.http.get(`${this.BASE_URL}${page}`) .map((response:Response) => response.json()) .catch((error:any) => Observable.throw(error.json().error) || 'Server Error'); } }
Nothing new Here just a get request with page number using observable. For now our application knows nothing about this service. We will use this service later in this article.
First thing First: The UI
Whenever you create any new application in angular 2 using Angular Cli, it ships with a default component inside app directory, so we will be using that component only.
app.component.html :
<!-- Server side pagination Angular 2 @author Shashank Tiwari --> <div class="container"> <h2>{{title}}</h2> <div class="pagination-data"> <table class="table"> <tr> <th>Name</th> <th>Age</th> <th>Country</th> </tr> <tr *ngFor = ' let user of users | paginate : { itemsPerPage:5, currentPage:page, id : 1, totalItems:15 } ' > <td>{{user.name}}</td> <td>{{user.age}}</td> <td>{{user.country}}</td> </tr> </table> <pagination-controls (pageChange) = "page = getServerData($event)" id="1" maxSize = "3" directionLinks = "true" autohide = "true" > </pagination-controls> </div> </div>
In the above code, there are two important things to notice,
- First, Paginate pipe with ngFor directive.
- Second, pagination-controls component.
ng2-pagination :
Paginate Pipe:
ng2-pagination provides a pipe where you need provide few parameters shown below,
Also, read Angular 2 Pipe: Create a custom Angular 2 Pipe
- itemsPerPage [ Number ]: This is required a parameter, which specifies the number of items to be rendered on each page.
- currentPage [ Number ] : Number of Current page.
- id [ String ]: Suppose you want a more than one pagination, then id comes to the rescue. it matches the id attribute of the pagination-controls component.
- totalItems [ Number ] : Useful in our case (server side pagination). This is a total number of items in the collection.
Pagination-controls component :
Basically, it renders the navigation links to paginate between the pages. This component requires some attributes listed below,
- (pageChange) [ $event ]: Is an event which gives the number of the page clicked in the navigation link.
- maxSize [ Number ] : Number of pages.
- id [ String ]: To link with Paginate pipe.
Now if you notice again I have written the below line in the pagination-controls component. In the below code, I am doing two things
(pageChange) = "page = getServerData($event)"
- I am calling
getServerData()
function by passing current page number($event), on click of the pagination links. - Assigning current page number($event), to the page attribute of the paginate pipe.
I hope till now everything is clear.
The component
app.component.ts :
/* * Server side pagination Angular 2 * @author Shashank Tiwari */ import { Component } from '@angular/core'; import { HttpService } from './http.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers: [HttpService] }) export class AppComponent { title = 'Simple Server side Angular 2 pagination'; users = []; constructor( private httpService : HttpService ){ this.getServerData(1); } public getServerData(event){ this.httpService.getdata(event).subscribe( response =>{ if(response.error) { alert('Server Error'); } else { this.users = response.users; this.totalItem = response.totalItems; } }, error =>{ alert('Server error'); } ); return event; } }
Here we have used the http
service, which we created earlier by importing it and providing it into the providers attribute of the component decorator.
In constructor method two things are happening first we are creating the private instance of the HTTP service. and second, we are calling getServerData()
method to load the first page.
In getServerData()
method, we have consumed thegetdata()
method of the HTTP service.
Conclusion
In this article, we created a simple Server side Pagination in Angular 2 with minimum complexity. Although there are other modules available for pagination in angular 2 but personally I found ng2-pagination easy to get started. If you have any question or suggestion Let me know in below comment box.
thanks for this tutorial, but i get a problem, “this.getServerData(1);” didn’t work and i can’t get the first page’s items, i got only the second ones , any help pleeeeease m stuck :/
Thanks, Can please check your console see if you are getting any error over there ?
i fixed it , thank you so much ^^
How did you fix it?
What if I want to see the details of a user when I am on page 3 and get a back button its going to take me back to page1 instead of 3 cause thats how I placed in the constructor
How would you handle that ?
There are multiple ways to achieve this. But in my opinion, using cookies would be very easy.
What you can do is, store the current page number in COOKIE and use that wherever you want.
Thank you.
What about /users from backend?
Hi, can you elaborate your question?
help! I am newbie in web develpment and I am not able to run this project
What is the issue you are getting?