• Download
  • Contact
  • Terms of Service
  • Privacy Policy
  • About US
Codershood
  • Demos
  • Plugins
  • Angular
  • NodeJs
  • GO lang
  • Others
No Result
View All Result
Codershood
  • Demos
  • Plugins
  • Angular
  • NodeJs
  • GO lang
  • Others
No Result
View All Result
Codershood
No Result
View All Result

Server side Pagination in Angular 2

by Shashank Tiwari
August 8, 2018
in Angular
10
4 Minutes Read
Server side Pagination Angular 2

Server side Pagination in Angular 2

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.

 

 Download

 

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.jsonas 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,

  1. First, Paginate pipe with ngFor directive.
  2. 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

  1. itemsPerPage [ Number ]: This is required a parameter, which specifies the number of items to be rendered on each page.
  2. currentPage [ Number ] : Number of Current page.
  3. 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.
  4. 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,

  1. (pageChange) [ $event ]: Is an event which gives the number of the page clicked in the navigation link.
  2. maxSize [ Number ] : Number of pages.
  3. 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)"

  1. I am callinggetServerData() function by passing current page number($event), on click of the pagination links.
  2. 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.

Tags: AngularPagination
Previous Post

Angular 2 Pipe : Create a custom Angular 2 Pipe

Next Post

Real time private chatting app using Angular 2, Nodejs, mongodb and Socket.io – Part 1

Related Posts

How to use Web Share API in your Angular applications
Angular

How to use Web Share API in your Angular applications

August 8, 2018
Implementing Swipe to delete in Angular
Angular

Implementing Swipe to delete in Angular

August 8, 2018
Building a 2D racing Game using Angular
Angular

Building a 2D racing Game using Angular

August 8, 2018
Next Post
Real time private chatting app using Angular 2, Nodejs, mongodb and Socket

Real time private chatting app using Angular 2, Nodejs, mongodb and Socket.io – Part 1

Comments 10

  1. rahma Nefai says:
    8 years ago

    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 :/

    Reply
    • Shashank says:
      8 years ago

      Thanks, Can please check your console see if you are getting any error over there ?

      Reply
      • rahma Nefai says:
        8 years ago

        i fixed it , thank you so much ^^

        Reply
        • Tsvetina Gramova says:
          8 years ago

          How did you fix it?

          Reply
  2. Prim ministrul tau says:
    8 years ago

    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 ?

    Reply
    • Shashank says:
      8 years ago

      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.

      Reply
  3. tenzolinho says:
    6 years ago

    What about /users from backend?

    Reply
    • Shashank Tiwari says:
      6 years ago

      Hi, can you elaborate your question?

      Reply
  4. pawan says:
    5 years ago

    help! I am newbie in web develpment and I am not able to run this project

    Reply
    • Shashank Tiwari says:
      5 years ago

      What is the issue you are getting?

      Reply

Leave a Reply Cancel reply

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




https://codershood.info

www.codershood.info programming blog dedicated to providing high-quality coding tutorial and articles on web development, Angular, React, Laravel, AngularJs, CSS, Node.js, ExpressJs and many more. We also provide ebook based on complicated web application along with the source code.

  • Download
  • Contact
  • Terms of Service
  • Privacy Policy
  • About US

www.codershood.info is licensed under a Creative Commons Attribution 4.0 International License.

No Result
View All Result
  • Demos
  • Plugins
  • Angular
  • NodeJs
  • GO lang
  • Others

www.codershood.info is licensed under a Creative Commons Attribution 4.0 International License.