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>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s