Search Pipe to Filter results with Angular 5

Tuesday, March 20, 2018

Step by step guide to implement search pipe to filter results with Angular 5. AngularJs will comes with inbuilt filter pipes.

But Angular didn't comes with filter pipes, because they perform poorly and prevent aggressive minification.

Step 1:

Install latest version of Angular Cli using following command.

npm install -g @angular/cli@latest

You can find the instruction and documentation in https://cli.angular.io/

Step 2: Create new project using Angular Cli

ng new myproject

It will create all required folder structure for you and install all node modules.

Step 3:

Create filter pipe filter.pipe.ts

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

@Pipe({

  name: 'filter'

})

export class FilterPipe implements PipeTransform {

 transform(items: any, term: any): any {
    if (term === undefined) return items;

    return items.filter(function(item) {
      for(let property in item){
        if (item[property] === null){
          continue;
        }
        if(item[property].toString().toLowerCase().includes(term.toLowerCase())){
          return true;
        }
      }
      return false;
    });
  }

}

Step 4:

Import filter pipe in app.module.ts

import { NgModule }      from '@angular/core';

import { FormsModule }   from '@angular/forms';

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';

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

@NgModule({

  imports:      [ BrowserModule, FormsModule ],

  declarations: [ AppComponent, FilterPipe ],

  bootstrap:    [ AppComponent ]

})

export class AppModule { }

Step 5:

app.component.html should now look like this

<input [(ngModel)]="searchCategory" placeholder="search text...">

<section>

  <div *ngFor="let cat of categories | filter : searchCategory">

    {{cat}}

  </div>

</section>

Note: The filter pipe given above will solve this error "TypeError: it.toLowerCase is not a function", if you are using default filter pipe.

You Might Also Like

0 comments