How to implement an Angular search filter in Angular 10 and 11?

In a real application, we might have a large list of data that we have displayed through a table using pagination but it would make users inconvenience and time-taking to search for any particular keyword in a long list without any search functionality provided. We can solve the above issues by providing users with input searches, where users can filter the data based on the user requirement. We need to implement an Angular search filter to array objects in the input text field.

In this tutorial we’ll explore how to add Angular seearch filter in our Angular project. There are different thirdparty libraries to used but we will used ng2-search-filter with two example. Lets get started.

How to implement an Angular search filter ?

We can implement an Angular search filter using our own custom filter pipe or we can use a third-party search filter library like ng2-search-filter. The ng2-search-filter library is open source and is only a 31.2 kB package, allow us to make custom search filters. In this tutorial, we will demonstrate both approaches to implement an Angular search filter. If you are using Angular material or bootstrap, or if any other UI frameworks, the best approach is to check if any available search filter on the framework.

Different ways to implements Angular search filter

Here we have listed different approaches to implementing Angular search filters.

Name of Angular search filterDescription
Angular bootstrap table search filterIf you are using Bootstrap for your angular project, then it is best to use the ng-bootstrap component. We have a complete tutorial on how to implement pagination and search filter on the data table using the ng-bootstrap library. Check here
Angular material search filterSame as bootstrap, if you are using Angular material UI, then it is best to use its components, which are ready to use.
ng2-search-filterThis is 3rd party library make custom search but it hasn’t update from last 2 year.
custom search filterWe can create our own search filter with help of angular pipes.

Setup and configure Angular search filter project

Let create first create an Angular project for the Angular search filter, name the project searchFilterApps.

ng new searchFilterApps

All we need is dummy data, so we that user search data based on filter criteria on search 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": "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": "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
    }
]

Example 1: Angular search filter using ng2-search-filter

We’ll demonstrate Angular search filter using third-party library ng2-search-filter. Here we first need to install the ng2-search-filter library in our project by following the command.

npm i ng2-search-filter --save

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

Angular search filter

To use ng2-search-filter we need to import Ng2SearchPipeModule in our app.module.ts file. We also need to import HttpClientModule to retrieve our data using the HTPP GET method.

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';

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

Add filter of ng2-search-filter in our component

First, we need a variable that can hold the list of data to be filtered. We can retrieve our data from countries.json using the HTTP GET method. Edit app.component.ts file.
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;
  countries: Country[];
  term: string;

  constructor(private http: HttpClient) { }

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

Once we have a list of data to filter, we need to have an input search bar, that allows a user to type his/her search criteria to filter. In our case, we have a countries array object that can filter using it name of the country. Edit app.component.html template to add a search bar.

<div class="m-3">
  <h3>Angular search by filter</h3>
  <div class="wrap">
    <div class="search">
      <input type="text" [(ngModel)]="term" class="searchTerm" placeholder="What are you looking for?">
    </div>

    <div *ngFor="let item of countries | filter:term">
      <p>
        {{ item.name }}
      </p>
    </div>
  </div>
</div>

<router-outlet></router-outlet>

As we have add | filter on ngFor loop of countries to implement search filter on countries by name. Whatever user type in searchbar that text data where it matches countries name will filter.

Example 2: Angular search filter using a custom filter pipe

We can achieve an Angular search filter without using any library. Angular has lots of predefined pipes, which allowed us to format and transform data.  Pipes are functions that we can use in template expression to format input data before it’s rendered. Angular has lots of its own built-in pipes and we can use pipe for synchronous and asynchronous data. Example of Angular built pipe like lowercase.
lowercase: <pre>'{{ 'EdUpALa'| lowercase}}'</pre> //Output edupala
Angular search filter example

Angular doesn’t have a search filter pipe, we will make our own custom search pipe to perform an Angular search filter on the input field. Let first create a custom pipe using the following command.

ng g pipe searchFilter

Edit search-filter.pipe.ts file to filter the list based on user type text criteria of input field data.

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

@Pipe({ name: 'searchFilter' })
export class SearchFilterPipe implements PipeTransform {

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

To filter data using our custom filter pipe, first, we need data and we are using some dummy data of countries.json of example one. Let edit the app.component.ts file to retrieve data. We have a search method to filter our data.

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;
  countries: Country[];
  allCountries: Country[];

  constructor(private http: HttpClient) { }

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

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

}

Edit the app.component.html template to add search bar input field and our custom searchFilter pipe on ngFor loop of the list.

<form class="wrap">
  <div class="search">
    <h3>Search country by name filter : </h3>
    <input class="searchTerm" type="text" name="searchTerm" placeholder="Filter by country name"
      [(ngModel)]="searchTerm" (input)="search($event.target.value)" />
  </div>
</form>

<table class="table table-striped">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Country</th>
      <th scope="col">Area</th>
      <th scope="col">Population</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let country of countries | searchFilter: searchTerm; index as i">
      <td scope="row">{{ i + 1 }}</td>
      <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>

<router-outlet></router-outlet>

We have use css class to style table and search bar input UI. Edit app.component.scss for style.

table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;

    th {
        background-color: red;
        border: 1px solid red;
    }
    td {
        border: 1px solid #dddddd;
    }
    td, th {
        text-align: left;
        padding: 8px;
    }
      
    tr:nth-child(even) {
        background-color: #dddddd;
    }
}
 
.wrap{
  .search {
    width: 100%;
    position: relative;
    display: flex;
  }
  
  .searchTerm {
    width: 100%;
    border: 3px solid #00B4CC;
    padding: 5px;
    height: 20px;
    border-radius: 5px;
    outline: none;
    color: #9DBFAF;
  }
  
  .searchTerm:focus {
    color: #00B4CC;
  }
  p{
      color: #383c52;
  }
}
form {
    input {
        width: 50% !important;
        margin: 2px 0 20px 20px;
    }
}

Conclusion
We have complete our Angular search filter using two approaches. First by ng2-search-filter and second by our own custom pipe to filter the list.

Related posts

2 thoughts on “How to implement an Angular search filter in Angular 10 and 11?”

Leave a Comment

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

Scroll to Top