Monday, 18 December 2017

Angular 4: Implementing server side Pagination

I have implemented server-side pagination in angular 4 using ngx-pagination plugin. Please check following easy steps to implement pagination:

Step 1: Install nuget package of ngx-pagination as following:
Command: npm install ngx-pagination --save




Step 2: Import module "NgxPaginationModule" in "app.module.ts" file as following.

import {NgxPaginationModule} from 'ngx-pagination'; // <-- import the module

@NgModule({
  imports: [
    NgxPaginationModule//add here
  ]
})

export class AppModule { }

Step 3: Modify your html view like following code.
<table id="customerTable" cellspacing="0" cellpadding="0">
  <caption>
    Customers
    <a href="/addCustomer" class="btn btn-red">+Add New</a>
  </caption>
  <thead>
    <tr>
      <th>Id</th>
      <th>Name</th>
      <th>Description</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let customer of customers | paginate: { itemsPerPage: itemPerPage, currentPage: p, totalItems: total };">
      <td>{{customer.id}}</td>
      <td>{{customer.name}}</td>
      <td>{{customer.description}}</td>
      <th>
        <a href="/editCustomer/{{customer.id}}" class="btn btn-grey">Edit</a>
        <a (click)="delete(customer.id)" href="javascript:void(0);" class="btn btn-red">Delete</a>
      </th>
    </tr>
  </tbody>
  <pagination-controls (pageChange)="pageChanged($event)"></pagination-controls>

</table>

Step 4: Modify your .ts file as following code:

import { Component, OnInit } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';

import { CustomerModel } from '../../models/customer.model';
import { AppSettings } from '../../constants/appsettings';

@Component({
  selector: 'app-root',
  templateUrl: './customers.html',
  styleUrls: ['./customers.css']
})
export class CustomersComponent implements OnInit {

  constructor(private _httpService: Http) { }

  private customers: CustomerModel[];

  //Pagination: initializing p to one
  p: number = 1;
  total: number = 0;
  itemPerPage: number = 5;
  pageChanged($event): void {
    this.p = $event;
    this.getCustomers()
  }

  ngOnInit() {
    this.getCustomers();
  }

  getCustomers() {
    var dataToPost = JSON.stringify({ pageNumber: this.p, itemsPerPage: this.itemPerPage });

    this._httpService.post(AppSettings.API_ENDPOINT + '/customer/GetCustomers', dataToPost, this.addHeaders()).subscribe(values => {
      var data = values.json();
      this.customers = data.Data;
      this.total = data.Total;
    });
  }

  private delete(id: number): void {
    var isConfirm = confirm("Are you sure?");

    if (isConfirm) {
      this._httpService.post(AppSettings.API_ENDPOINT + '/customer/DeleteCustomer/' + id, {}).subscribe(values => {
        let index = this.customers.findIndex(x => x.id === id); //find index in your array
        this.customers.splice(index, 1);//remove element from array
      });
    }
  }

  addHeaders() {
    let headers = new Headers();
    let params = new URLSearchParams();
    headers.append('Content-Type', 'application/json');
    let options = new RequestOptions({ headers: headers, params: params });
    return options;
  }

}

Step 5: Apply following changes in your server side code:
namespace WebAPI.Controllers
{
    [RoutePrefix("api/customer")]
    public class CustomerController : ApiController
    {
        static List<Customer> customers = new List<Customer>();
        public CustomerController()
        {
            if (customers.Count == 0)
            {
                for (int i = 0; i < 10; i++)
                {
                    customers.Add(new Customer
                    {
                        id = i,
                        name = "Customer" + i,
                        description = "Description" + i
                    });
                }
            }
        }

        [Route("GetCustomers")]
        [HttpPost]
        public IHttpActionResult GetCustomers(PagedModel model)
        {
            PagedResponse<List<Customer>> pagedData = new PagedResponse<List<Customer>>();
            pagedData.Total = customers.Count();
            double pageCount = (double)(pagedData.Total / model.ItemsPerPage);
            pagedData.NumberOfPages = (int)Math.Ceiling(pageCount);

            int pageToSkip = (model.PageNumber - 1) * model.ItemsPerPage;

            pagedData.Data = customers.Skip(pageToSkip).Take(model.ItemsPerPage).ToList();

            return Ok(pagedData);
        } 
    }
}

public class Customer
{
    public int id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
}
public class PagedResponse<T>
{
    public int Total { get; set; }
    public int NumberOfPages { get; set; }
    public T Data { get; set; }
}
public class PagedModel
{
    public int PageNumber { get; set; }
    public int ItemsPerPage { get; set; }

}

No comments:

Post a Comment