Angular2: Creating custom search filter pipe for ngFor directive

Standard

As you are aware of the fact that, Filters in Angular 1.x have been replaced with pipes in Angular2, unfortunately, search filter for ng-repeat has been dropped in Angular2. So in order to select a subset of items from an array and returns it as a new array for the *ngFor directive, we have to create our own custom pipe.

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

@Pipe({
 name: 'searchfilter'
})

@Injectable()
export class SearchFilterPipe implements PipeTransform {
 transform(items: any[], field: string, value: string): any[] {
   if (!items) return [];
   return items.filter(it => it[field] == value);
 }
}

You need to register the pipe within your module:

@NgModule({
 imports: [
   BrowserModule,
   HttpModule,
   FormsModule,
  ],
 declarations: [
   AppComponent,
   SearchFilterPipe
  ],
 providers: [
   All_Services
  ],
 bootstrap: [
   AppComponent
  ],
 schemas: [
   CUSTOM_ELEMENTS_SCHEMA
  ]
})

Html code:

<input #txtFname placeholder="first name" />
<tr *ngFor="let item of mylst | searchfilter: 'fname' : txtFname.value">
  <td>
      {{item.fname}}
  </td>
  <td>
      {{item.lname}}
  </td>
</tr>

3 thoughts on “Angular2: Creating custom search filter pipe for ngFor directive

Leave a comment