Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

A Guide to Implementing Robust Angular Search Filters in Angular 16| 17

Angular search filter example

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 inconvenienced 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 requirements. 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 an Angular search filter in our latest Angular 17 version. There are different approaches to adding a search filter in Angular; we can use custom pipes to create the search filter. We will demonstrate few examples. Let’s 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 it allowing us to make custom search filters but this library had not update from last 4 years. We can easily implement search filter without using any third parites. If you are using Angular material bootstrap, or any other UI frameworks, the best approach is to check if any available search filter on the framework.

Different ways to implement 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 filters 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 that makes a custom search but it hasn’t been updated for the last 2 years.
custom search filterWe can create our own search filter with help of angular pipes.
Angular search

Set Up and Configure Angular Search Filter Project

Before delving into the implementation of the Angular search filter project, we need to set up an Angular project. To get started, create our Angular project using the ng command

Let’s first create an Angular project for the Angular search filter and name the project ‘searchFilterApps’.

ng new searchFilterApps
cd searchFilterApps

All we need is dummy data so that users can search data based on filter criteria in the search input. We will add it directly to the component where we are using it.

Angular search filter example using a custom filter pipe

We can achieve an Angular search filter without using any library. Angular has lots of predefined pipes that allow us to format and transform data. Pipes are functions that we can use in template expressions to format input data before it’s rendered.

Angular has lots of its own built-in pipes and we can use pipes for synchronous and asynchronous data. Example of Angular-built pipe like lowercase.

lowercase: <pre>'{{ 'EdUpALa'| lowercase}}'</pre> //Output edupala

Here is our screenshot of Angular search filter using custom pipe.

Angular search filter example
Angular search example using custom pipe

Step 1: Create custom search pipe

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

ng g pipe searchFilter

Edit the ‘search-filter.pipe.ts’ file to filter the list based on the user-typed text criteria in the input field.

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

@Pipe({
  name: 'searchFilter',
  standalone: true,
})
export class SearchFilterPipe implements PipeTransform {
  transform(list: any[], filterText: string): any {
    return list
      ? list.filter(
          (item) => item.name.search(new RegExp(filterText, 'i')) > -1
        )
      : [];
  }
}

Step 2: Import and Add Custom Search Filter Method in Component

To filter data using our custom filter pipe, first, we need to import it inside our component where we are using it. We also need some dummy data to perform the search filter. Let’s edit the ‘app.component.ts’ file to retrieve data. We have a search method to filter our data.

import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { SearchFilterPipe } from "./search-filter.pipe";

@Component({
    selector: 'app-root',
    standalone: true,
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
    imports: [CommonModule, RouterOutlet, FormsModule, SearchFilterPipe]
})
export class AppComponent implements OnInit {
  searchTerm: string = '';
  filteredItems: Array<{
    name: string;
    flag: string;
    area: number;
    population: number;
  }> = [];

  countries: Array<{
    name: string;
    flag: string;
    area: number;
    population: number;
  }> = []; // Declare countries array

  ngOnInit(): void {
    // Initialize countries array
    this.countries = [
      {
        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,
      },
    ];
  }

  search(searchTerm: string) {
    this.searchTerm = searchTerm.toLowerCase();
  }

  filterItems(searchTerm: string) {
    this.filteredItems = this.countries.filter((item) =>
      item.name.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }
}

Next, implement the filter functionality when user start typing on search input. Create a method that takes a search term as a parameter and updates the filteredItems array virables based on the search term.

Step 3: Used our custom search custom filter in component template

Edit the app.component.html template to add the search bar input field and our custom searchFilter pipe on the 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(searchTerm)" />
  </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>
  <input type="text" [(ngModel)]="searchTerm" placeholder="Search" />

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Area</th>
    </tr>
  </thead>
  <tbody>
    <tr
      *ngFor="let country of countries | searchFilter : searchTerm; index as i"
    >
      <td>{{ country.name }}</td>
      <td>{{ country.area }}</td>
    </tr>
  </tbody>
</table>

<router-outlet></router-outlet>

We have to use a CSS class to style the table and search bar input UI. Edit the 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;
    }
}

Related posts

A Guide to Implementing Robust Angular Search Filters in Angular 16| 17

4 thoughts on “A Guide to Implementing Robust Angular Search Filters in Angular 16| 17

  1. export class AppComponent implements OnInit {
    searchTerm: string;
    countries: Country[];
    allCountries: Country[];

    How to initialise these variables

Leave a Reply

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

Scroll to top