Searching and Pagination for a normal HTML table in Angular

Hey guys, in this post we are going to see how to create features like searching and pagination in normal HTML Table in Angular. Let’s do it step by step.
We are going to use our same previous example to implement these features.
Let's create the normal HTML page which will contain a table.

[ If you are preparing for an interview please click here - angular interview questions and answers ]
[At the bottom, you will get the link to download the project ]

home.component.html
<div class="container card">
  <div class="row">
    <div class="col-lg-12">
      <label for="">Searching and pagination demo</label>
      <div style="float:right">
        <input type="text" placeholder="search by name" #searchVal (keyup)="search(searchVal.value)">
      </div>
    </div>
    <div class="col-lg-12">
      <table class="table table-striped">
        <thead>
          <th>Id</th>
          <th>User Name</th>
          <th>Email</th>
          <th>contact No</th>
          <th>Address</th>
        </thead>
        <tbody>
          <tr *ngFor="let user of userList; index as i">
            <td *ngIf="i >= firstItemIndex && i < lastItemIndex">{{user.id}}</td>
            <td *ngIf="i >= firstItemIndex && i < lastItemIndex">{{user.userName}}</td>
            <td *ngIf="i >= firstItemIndex && i < lastItemIndex">{{user.email}}</td>
            <td *ngIf="i >= firstItemIndex && i < lastItemIndex">{{user.contactNo}}</td>
            <td *ngIf="i >= firstItemIndex && i < lastItemIndex">{{user.address}}</td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <td colspan="5">
              <div style="float:right">
                <div class="btn btn-sm btn-light" (click)="onPreviousPageClick($event)">
                  < </div> <div class="btn btn-sm btn-light" (click)="onNextPageClick($event)">
                    >
                </div>
              </div>
            </td>
          </tr>
        </tfoot>
      </table>
    </div>
  </div>
</div>


Here we have created a table with user data and two buttons to go to the next page and previous page, and one input box to accept search value.
Here, we have the logic.

home.component.ts
import { Component, OnInit } from '@angular/core';
import { user } from '../user/user';

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

  private userList: user[];
  private userListBackup: user[];
  firstItemIndex: number;
  lastItemIndex: number;
  pagesize: number = 5;

  constructor() { }

  ngOnInit() {
    this.getAlldata();
    this.firstItemIndex = 0;
    this.lastItemIndex = 5;
  }

  getAlldata() {
    this.userList = [
      { id: 1, userName: "Ramesh", password: "rebqwtye", email: "ramesh@gmail.com", contactNo: "9788235466", address: "123 RG Road, XYCity" },
      { id: 2, userName: "Suresh", password: "rebqwtye", email: "suresh@gmail.com", contactNo: "9750235444", address: "446 RG Road, XYCity" },
      { id: 3, userName: "Ganesh", password: "rebqwtye", email: "ganesh@gmail.com", contactNo: "9789235422", address: "765 RG Road, XYCity" },
      { id: 4, userName: "Bhavesh", password: "rebqwtye", email: "bhavesh@gmail.com", contactNo: "9728235466", address: "123 RG Road, XYCity" },
      { id: 5, userName: "Bhavesh", password: "rebqwtye", email: "bhavesh@gmail.com", contactNo: "9748235466", address: "78 RG Road, XYCity" },
      { id: 6, userName: "Bhavesh", password: "rebqwtye", email: "bhavesh@gmail.com", contactNo: "9786235466", address: "123 RG Road, XYCity" },
      { id: 7, userName: "Bhavesh", password: "rebqwtye", email: "bhavesh@gmail.com", contactNo: "9788237466", address: "123 RG Road, XYCity" }
    ];
    this.userListBackup = Object.create(this.userList);
  }

  onNextPageClick(data: any) {
    this.firstItemIndex = this.lastItemIndex < (this.userList.length - 1) ? this.lastItemIndex : this.firstItemIndex;
    this.lastItemIndex = (this.lastItemIndex + this.pagesize) < this.userList.length ? (this.lastItemIndex + this.pagesize) : (this.userList.length - 1);
  }

  onPreviousPageClick(data: any) {
    this.lastItemIndex = this.firstItemIndex > 0 ? this.firstItemIndex : this.lastItemIndex;
    this.firstItemIndex = (this.firstItemIndex - this.pagesize) > 0 ? (this.firstItemIndex - this.pagesize) : 0;
  }

  search(searchValue: String) {
    if (!searchValue) {
      this.userList = Object.create(this.userListBackup);
    } else {
      this.userList = this.userListBackup.filter(user =>
        JSON.stringify(user).trim().toLowerCase().includes(searchValue.trim().toLowerCase())
      );
    }
  }
}


Searching:
Here, at very first we have populated user list with dummy data and taken other copy of that data to search the value.
 we have used other copy of data, because in the search box when we search for any value we get some result, If we accept the result in the same array then we lose our original data. So when we search for (eg. “bhav”) we will get some records but suppose we erase something (eg. “bh”) then we must have to return additional records which are currently matching with a search field that’s why we have maintained two copies of data.
On keyup we have searched matching string in our backup list, we called stringify method on the object because we want to search given string in all fields/properties of the object. And Lowercase function to make search case insensitive.
Pagination:
Implementation of pagination is very simple, here we have made a page of five records(you can make it of any size or variable size, once you understand its working).  To achieve pagination we have maintained first and Last index, we are making those record visible who's indexes comes in firstItemIndex and lastItemIndex variable. At very first firstItemIndex is 0 and LastItemIndex is 5 so only five records will be displayed, when user press next page button, firstItemIndex becomes lastItemIndex and lastItemIndex is increased by five. Same is applicable for the previous page, the only difference is, instead of adding value to index just subtract it from firstItemIndex(and few checks for first and last page). Everything you can understand very easily by looking at the code.

This is the module file to let you know the dependencies and imports needed for this tutorial
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FirstPageComponent } from './first-page/first-page.component';
import { SecondPageComponent } from './second-page/second-page.component';
import { FormsModule } from '@angular/forms';
import { HomeComponent } from './home/home.component';
import { HttpClientModule } from '@angular/common/http';
import { GoogleChart } from '../app/angular2-google-chart.directive';

@NgModule({
declarations: [
AppComponent,
FirstPageComponent,
SecondPageComponent,
HomeComponent,
GoogleChart
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Here is output:

We are done with the implementation of searching and pagination in the normal HTML table.

 [Click here to download the project:get me the project]

Comments