How to implement an Angular bootstrap table with pagination and filter

In Angular, we can implement a table in different ways, in this tutorial we’ll learn and demonstrate the Angular bootstrap table in Angular 11. Angular Bootstrap table component is responsive tables that allow us to filter, pagination, and table can have nice UI by using bootstrap style class name.

To implement the bootstrap table in Angular is recommend to use the ng-bootstrap library instead of the whole bootstrap. The ng-bootstrap is built specifically for Angular by the Bootstrap team, allow us to use Bootstrap components and directives in Angular.  Bootstrap uses plain JavaScript and JQuery and Angular use Typescript. So it would not be recommended to use Bootstrap directly in Angular and it may cause an issue while dealing with JavaScript of Bootstrap and JQuery. But we can still use the CSS part of it, the ngx-bootstrap library that is compatible with Angular and doesn’t need JQuery.

In this tutorial, we will learn how to implment angular table using bootstrap. Will demonstrate an example with angulart tables with filter, pagination and image on table contents. Let’s get started.

We’ll demonstrate here’s a quick screenshot of what we’ll be building.

Angular bootstrap table

What we are learning?

  • Angular ng-bootstrap table using the HTTP GET method
  • Angular ng-bootstrap table pagination
  • Angular ng-bootstrap table search filter

Setting up a project for angular bootstrap table

Let create our angular project for Angular bootstrap table apps, name the project bootstrapTable. We need to install the ng-bootstrap library. We need to create a custom pipe called listFilter, so that we can filter our table data using search input.

ng new bootstrapTable
ng add @ng-bootstrap/ng-bootstrap

Create a pipe for Angular bootstrap table filter

We need to create an Angular custom pipe to filter the countries data by name of the country. In the app.component.html template, we have an input field where we allow users to type or search countries by name. Create file listFilterPipe.ts file in the app folder or for your project you can have folder pipes where you add all pipe files. Edit listFilterPipe.ts.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'listFilter'})
export class ListFilterPipe implements PipeTransform {

    transform(list: any[], filterText: string): any {
        return list ? list.filter(item => item.name.search(new RegExp(filterText, 'i')) > -1) : [];
    }
}

Once we have created our project and install the ng-bootstrap library and we need to import the ng-bootstrap module called NgbModule in our app.module.ts file so that we can use the ng-bootstrap component in our angular project. In our case, we are using the Bootstrap table and pagination component. We also need to declare our custom filter pipe in the declaration list in the app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { ListFilterPipe } from './listFilterPipe';

@NgModule({
  declarations: [
    AppComponent,
    ListFilterPipe
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule,
    NgbModule
  ],
  providers: [ ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Importing bootstrap CSS in our project

The ng-bootstrap in Angular includes the only component but we need to import the Bootstrap style in our project. To make the Bootstrap CSS classes available for the ng-bootstrap in angular components in our project we need to include the Bootstrap CSS in our index.html file in src as

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

Angular version 10 need bootstrap 4.5.0 CSS and you need to check Bootstrap compatibility with angular on ng-bootstrap compatibility on npmjs site.

Create data for Angular Bootstrap table example

All we need is an array of data to display on the table and we can filter on and an input field to filter user input. Let’s first create dummy countries data and create a folder called data in the assets folder and add a file called countries.json inside the data folder.

[
    {
      "name": "Russia",
      "flag": "f/f3/Flag_of_Russia.svg",
      "area": 17075200,
      "population": 146989754
    },
    {
      "name": "France",
      "flag": "c/c3/Flag_of_France.svg",
      "area": 640679,
      "population": 64979548
    },
    {
      "name": "Germany",
      "flag": "b/ba/Flag_of_Germany.svg",
      "area": 357114,
      "population": 82114224
    },
    {
      "name": "Portugal",
      "flag": "5/5c/Flag_of_Portugal.svg",
      "area": 92090,
      "population": 10329506
    },
    {
      "name": "Canada",
      "flag": "c/cf/Flag_of_Canada.svg",
      "area": 9976140,
      "population": 36624199
    },
    {
      "name": "Vietnam",
      "flag": "2/21/Flag_of_Vietnam.svg",
      "area": 331212,
      "population": 95540800
    },
    {
      "name": "Brazil",
      "flag": "0/05/Flag_of_Brazil.svg",
      "area": 8515767,
      "population": 209288278
    },
    {
      "name": "Mexico",
      "flag": "f/fc/Flag_of_Mexico.svg",
      "area": 1964375,
      "population": 129163276
    },
    {
      "name": "United States",
      "flag": "a/a4/Flag_of_the_United_States.svg",
      "area": 9629091,
      "population": 324459463
    },
    {
      "name": "India",
      "flag": "4/41/Flag_of_India.svg",
      "area": 3287263,
      "population": 1324171354
    },
    {
      "name": "Indonesia",
      "flag": "9/9f/Flag_of_Indonesia.svg",
      "area": 1910931,
      "population": 263991379
    },
    {
      "name": "Tuvalu",
      "flag": "3/38/Flag_of_Tuvalu.svg",
      "area": 26,
      "population": 11097
    },
    {
      "name": "China",
      "flag": "f/fa/Flag_of_the_People%27s_Republic_of_China.svg",
      "area": 9596960,
      "population": 1409517397
    }
]

Displaying Angular bootstrap table on component template

We have configured all settings for the Angular bootstrap table, to apply pagination we need to have information about a page number, page size, and a total number of data to display on the table. The ng-bootstrap pagination component will not manipulate data but it only helps us to display page numbers and navigate to each list using pagination buttons. The pagination component will split your data collection into pages yourself. For the pagination component, we have supplied the following value.

pageSizeNumber of elements/items per page
pageThe current page.
collectionSizeThe number of elements/items in the collection. i.e. the total number of items the pagination should handle.

Edit app.component.ts file, we can implement Angular ng-bootstrap table and pagination by rxjs Observable. But in this case, we have to use the Angular HttpClient GET method and javascript array object filter methods for pagination and filter search.

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

interface Country {
  name: string;
  flag: string;
  area: number;
  population: number;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  searchTerm: string;
  page = 1;
  pageSize = 4;
  collectionSize: number;
  currentRate = 8;
  countries: Country[];
  allCountries: Country[];


  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.http.get<Country[]>('./assets/data/countries.json')
      .subscribe((data: Country[]) => {
        this.collectionSize = data.length;
        this.countries = data;
        this.allCountries = this.countries;
      });
  }

  search(value: string): void {
    this.countries = this.allCountries.filter((val) => val.name.toLowerCase().includes(value));
    this.collectionSize = this.countries.length;
  }

}

Edit the app.component table to include search field, table data, and pagination as

<div class="m-3">
  <p>Angular ng-bootstrap table : filter and pagination</p>
  <form>
    <div class="form-group form-inline">
      Search country by name: 
<input class="form-control ml-2" type="text" name="searchTerm" [(ngModel)]="searchTerm"
        (input)="search($event.target.value)" />
    </div>
  </form>
  <table class="table table-striped">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col" sortable="name">Country</th>
        <th scope="col" sortable="area">Area</th>
        <th scope="col" sortable="population">Population</th>
      </tr>
    </thead>
    <tbody>
      <tr
        *ngFor="let country of countries | listFilter: searchTerm | slice: (page-1) * pageSize : page * pageSize; index as i">
        <th scope="row">{{ (page -1) * pageSize + i + 1 }}</th>
        <td>
          <img [src]="'https://upload.wikimedia.org/wikipedia/commons/' + country.flag" class="mr-2"
            style="width: 20px">
          {{ country.name }}
        </td>
        <td>{{ country.area | number }}</td>
        <td>{{ country.population | number }}</td>
      </tr>
    </tbody>
  </table>

  <ngb-pagination [collectionSize]="collectionSize" [(page)]="page" [maxSize]="5" [boundaryLinks]="true"
    [pageSize]="pageSize" class="d-flex justify-content-center"></ngb-pagination>
</div>
<router-outlet></router-outlet>

In ngFor we have applies our listFilter pipe, when a user types something it fills filter countries based on user input type and will display only countries that meet type conditions.

Conclusion
We have complete our Angular bootstrap table with pagination and search filter example. We can easily implement an Angular table without using any library and check our previous tutorial on implement an Angular table using a plain HTML table tag. If your project is using Angular material and then you can use the Angular material table component and it has a lot of built-in features like pagination, sorting, and filter.

Related Articles

1 thought on “How to implement an Angular bootstrap table with pagination and filter”

Leave a Comment

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

Scroll to Top