In this blog you will learn how to make reusable filter pipes for angular components. The below code snippet will work for both array and array of objects.
- import { Pipe, PipeTransform } from '@angular/core';
- @Pipe({
- name: 'tableFilter',
- pure: false
- })
- export class TableFilterPipe implements PipeTransform {
- transform(value: any[], searchText: string, prop?: any): any {
- if (!value) {
- return [];
- }
- if (!searchText || !prop) {
- return value;
- }
- const _searchText = searchText.toLowerCase(),
- _isArr = Array.isArray(value),
- _flag = _isArr && typeof value[0] === 'object' ? true : _isArr && typeof value[0] !== 'object' ? false : true;
- return value.filter(ele => {
- let val = _flag ? ele[prop] : ele;
- return val.toString().toLowerCase().includes(_searchText);
- });
- }
- }
Example configuration
- Search : <input type="text" [(ngModel)]="searchText">
- <br><br>
- <table border="1">
- <tbody>
- <tr *ngFor="let item of data | tableFilter:searchText:'name'">
- <td>{{item.name}}</td>
- <td>{{item.price}}</td>
- </tr>
- </tbody>
- </table>
Stackblitz demo : https://angular-filter-demo.stackblitz.io
Let me know if you're facing any issue related to this.
Cheers!!

Ila RamPosted Jun 29, 2020, 4:06 PM
Thanks for this. How do I extend the search to multiple columns?
ShanthBabu SPosted Feb 7, 2019, 5:23 AM
Hi Karthikeyan, this is Shanth Babu, I would like to talk to you. Can you get me how could I reach you? My email id is: [email protected]
ShanthBabu SPosted Feb 7, 2019, 4:07 AM
Hi Karthikeyan, this is Shanth Babu from Coimbatore, I would like to talk to you. Can you get me how could I reach you? My email id is [email protected]