Skip to content

Instantly share code, notes, and snippets.

@jamlfy
Last active July 10, 2019 18:18
Show Gist options
  • Save jamlfy/3bb60ad58de6d8a23f98d69e53a0690d to your computer and use it in GitHub Desktop.
Save jamlfy/3bb60ad58de6d8a23f98d69e53a0690d to your computer and use it in GitHub Desktop.
Search on pipe in Angular2
import { Pipe, PipeTransform, Injectable } from '@angular/core';
/**
*
* <input [(model)]="query" type="text" />
* <ul>
* <li *ngFor="let hero of heroes | search:query" >{{hero.name}}</li>
* </ul>
*/
@Pipe({
name: 'search',
pure: false
})
@Injectable()
export class search implements PipeTransform {
transform(items:any[], args:any):any[] {
var isSearch = (data:any): bool => {
var isAll = false;
if(typeof data === 'object' ){
for (var z in data) {
if(isAll = isSearch(data[z]) ){
break;
}
}
} else {
if(typeof args === 'number'){
isAll = data === args;
} else {
isAll = data.toString().match( new RegExp(args, 'i') );
}
}
return isAll;
};
return items.filter(isSearch);
}
}
@cozyazure
Copy link

Two nitpicks:

  1. The double binding should be [(ngModel)] instead of [(model)]
  2. typings should be boolean instead of bool at line 18.

Other than that, good gist 👍

@akash-agsft
Copy link

Great Pipe! Working perfectly.

@craftpip
Copy link

Thank you for the pipe ! 👍

@wiemKh
Copy link

wiemKh commented Aug 8, 2018

Thank you !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment