16

Example of Angular 4 Pagination Using ngx-pagination

 3 years ago
source link: https://www.js-tutorials.com/angularjs-tutorial/html-table-listing-pagination-using-angular-4/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Example of Angular 4 Pagination Using ngx-pagination

This tutorial help to implement Angular 4 pagination into HTML table using ngx-pagination.I will demonstrate how to implement HTML listing with pagination using Angular 2 and angular 4. I will use HTTP rest call to get data from the server in JSON format and display into HTML.I have shared Getting started with Angular 4 tutorial.I am extending that angular tutorial and create new one for pagination.We will add HTML table listing and pagination.

I am not using server-side pagination So all data will comes once at the time of the load page. You can convert the pagination server side using send extra parameters like current page and number of records in a page.

I will use ngx pagination module to create pagination using angular 2/4.You can install ngx-pagination using npm command 'npm install ngx-pagination --save'.Its internally using foundation css framework but you can override pagination css with bootstrap with extra effort.

I will use following files into this angular pagination tutorial:

  • package.json : This file will use to install require dependency module.
  • angular-cli.json : I will include all js and css file into this file.
  • app.component.html : This file is directive template that contains the html for displaying listing and pagination.
  • app.component.ts : This file help to controls models and view.
  • app.module.ts : This file use to inject require modules for this componenets.
  • app.service.ts : This is a service file which will have all methods to communicate server side rest api.You can inject this service anywhere into your application and use HTTP service.

Angular 4 Pagination Using ngx-pagination

We can create a sample app using the angular command line, I will also add the dependency bootstrap like if you want to use bootstrap CSS into angular 4, jquery etc. We will use PHP rest API to get all employee data from the server in JSON format and store into a variable.

I am assuming you have angular 4 or angular 2 sample project, I have 'simple-angular4-pagination' folder if not please create using Angular 4 from scratch tutorial. Now open package.json file and add below dependencies.

"bootstrap": "^v4.0.0-alpha.6",
"jquery": "^3.2.1",
"ngx-pagination": "^3.0.1",

You can skip last line if you have already installed ngx pagination module.I have included bootstrap 4 module, if you dont need then skipped above jquery and bootstrap module entry.

Now run below command on the root of your angular 4 project,

d:/simple-angular4-pagination > npm install
angular2-pagination-using-jquery

Added below bootstrap css and js path reference into angular-cli.json file,

"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
"../node_modules/datatables.net-dt/css/jquery.dataTables.css",
"styles.css"
  "scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/datatables.net/js/jquery.dataTables.js"

We will create app.service.ts file and added below code into this file, I am defining main rest api hosturl and using GET call to get all employee data from php rest api server.

import { Injectable } from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {Http, Response, RequestOptions, Headers} from '@angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
import { CommonModule } from '@angular/common';
@Injectable()
export class EmployeeService {
//the URL of the REST API
private servUrl = "http://localhost/api/v1/employees";
constructor(private http: Http) { }
//method to get all employee
getEmployees(): Observable<Response> {
    return this.http.get(this.servUrl);

You need to replace 'http://localhost/api/v1/employees' url with your API hosturl.

Open app.module.ts file and below code, I will inject EmployeeService so that we can access getEmployee() method into controller file.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {HttpModule} from '@angular/http';
import { CommonModule } from '@angular/common';
import {EmployeeService} from './app.service';
import {NgxPaginationModule} from 'ngx-pagination'; // <-- import the module
@NgModule({
  declarations: [
    AppComponent
  imports: [
    BrowserModule,
NgxPaginationModule,
HttpModule,
    CommonModule
  providers: [EmployeeService],
  bootstrap: [AppComponent]
export class AppModule { }

We have created Angular HTTP service to get employee data from server and injected into app modules, Now open app.component.ts file which will have logic to handle HTML and model.You need to add below code into this file:

import { Component } from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {Headers, Response} from '@angular/http';
import {EmployeeService} from './app.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  title = 'app';
  employees: Array<any>;
  totalRec : number;
  page: number = 1;
  //Constructor injected with the Service Dependency
    constructor(private serv: EmployeeService) {
        this.employees = new Array<any>();
    //4. Load all Employees
    ngOnInit() {
console.log('gggg');
        this.loadEmployee();
    private loadEmployee() {
            .serv
            .getEmployees()
            .subscribe((resp: Response) => {
                this.employees = resp.json();
                this.totalRec = this.employees.length;
                console.log(this.totalRec);
                console.log(this.page);
                //console.log(JSON.stringify(resp.json()));    

You can see above code, I have created loadEmployee() method to access service method to get data and assign to employee array type variable. I am using loadEmployee() method on initializing an app so that data will available at the time of app bootstrap.

We will edit app.html.ts file to add some HTML code for view, created html table and iterate on employee json data. We will bind single employee data with a row and display. Added below code into app.component.ts file.

<!--The content below is only a placeholder and can be replaced.-->
<div class="container">
  <h1>
    HTML table listing and pagination Using Bootstrap and Angular 4
  </h1>
  <table class="table table-bordered table-striped">
<thead>
<tr>
<td>Id</td>
<td>EmpNo</td>
<td>EmpName</td>
<td>Salary</td>
</tr>
</thead>
<tbody>
<tr *ngFor="let emp of employees | paginate: { id: 'listing_pagination',
                                                      itemsPerPage: 10,
                                                      currentPage: page,
                                                      totalItems: totalRec }">
  <td>{{emp.id}}</td>
  <td>{{emp.employee_name}}</td>
  <td>{{emp.employee_salary}}</td>
  <td>{{emp.employee_age}}</td>
</tr>
</tbody>
</table>
<div>
<pagination-controls  id="listing_pagination" maxSize="5" directionLinks="true" (pageChange)="page = $event"></pagination-controls>
</div>
</div>

'pagination-controls' is the ngx-pagination module directive, which is responsible to show pagination as per passed parameters.

Conclusion

I have created HTML table listing and demonstrated how to communicate view, service and controller class in angular4/2.We have created a separate service class to communicate to the server rest API. You can use bootstrap pagination nav bar as well but need to create you own custom pagination service class.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK