How to create a search filter in Angular

Puneet Billing
2 min readSep 12, 2020

--

You guessed it right, we are going to use a custom Pipe!

We are going to build a Search feature to filter cities of United States by name.

So, all you need is an array of data to filter on and an input field to grab user input. In this example it’s list of cities to be filtered by city name.

Step 1: Generate a pipe using ng g pipe <name>or manually write a Pipe class and implement PipeTransform interface.

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

@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {

transform(value: unknown, ...args: unknown[]): unknown {
return null;
}

}

Angular invokes the transform method with the value of a binding as the first argument, and any parameters as the second argument in list form, and returns the transformed value.

The above default transform method is not doing anything yet. Let’s make the magic happen.

Step 2: Write logic to filter data

// value - array of cities
// input - user input in search box
// when there is an input, filter & return all matches
// when there is no input, display all data
// filter() is a javascript method that returns a new array of all values that pass a test defined in the method. You can read more here
transform(value: any, input: any): any {
if (input) {
return value.filter(val => val.indexOf(input)) >= 0);
} else {
return value;
}
}

That’s it. done. 😀

Kidding! we still have to link this pipe to HTML template to get the data flowing.

Step 3: Don’t forget to include the custom pipe as a declaration in your app module:

import { FilterPipe } from './filter/filter.pipe';

Step 4: Now add custom pipe (in this example FilterPipe ) to your HTML template as:

//cityName gets user input that is passed to Pipe transform method mentioned in Step 1<input type="search" [(ngModel)] = cityName><div *ngFor="let city of cities | FilterPipe: cityName">
{{city}}
</div>

Use ngModelto bind dynamic input from user to cityName

That’s all.
Live at https://findthycity.herokuapp.com

GitHub: https://github.com/puneetpalkaur/findthycity

Official Angular doc: https://angular.io/guide/pipes

--

--

Puneet Billing
Puneet Billing

Written by Puneet Billing

I’m a software engineer. I love programming and teaching CS and Maths.

Responses (2)