Skip to content

Instantly share code, notes, and snippets.

@ranakrunal9
Created November 18, 2016 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ranakrunal9/092d6b930ede855e59e82c0f429fd562 to your computer and use it in GitHub Desktop.
Save ranakrunal9/092d6b930ede855e59e82c0f429fd562 to your computer and use it in GitHub Desktop.
Search Pipe Angular 2
<!-- Pipe Usage in HTML -->
<input placeholder="keyword..." [(ngModel)]="search"/>
<div *ngFor="let item of items | searchPipe:'name':search ">
{{item.name}}
</div>
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name : 'searchPipe',
})
export class SearchPipe implements PipeTransform {
public transform(value, key: string, term: string) {
return value.filter((item) => {
if (item.hasOwnProperty(key)) {
if (term) {
let regExp = new RegExp('\\b' + term, 'gi');
return regExp.test(item[key]);
} else {
return true;
}
} else {
return false;
}
});
}
}
@sanjaybhaskar
Copy link

Suppose the input field is in the different component/html will the model trigger the pipe to filter out on the input text?

@Jeklah
Copy link

Jeklah commented Mar 4, 2019

How can I modify this so it would work for searching for each word entered in the input field?

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