Angular 7 Table Reusable Filter Pipe

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.
  1. import { Pipe, PipeTransform } from '@angular/core';  
  2.   
  3. @Pipe({  
  4.   name: 'tableFilter',  
  5.   pure: false  
  6. })  
  7. export class TableFilterPipe implements PipeTransform {  
  8.   
  9.   transform(value: any[], searchText: string, prop?: any): any {  
  10.     if (!value) {  
  11.       return [];  
  12.     }  
  13.     if (!searchText || !prop) {  
  14.       return value;  
  15.     }  
  16.     const _searchText = searchText.toLowerCase(),  
  17.       _isArr = Array.isArray(value),  
  18.       _flag = _isArr && typeof value[0] === 'object' ? true : _isArr && typeof value[0] !== 'object' ? false : true;  
  19.   
  20.     return value.filter(ele => {  
  21.       let val = _flag ? ele[prop] : ele;  
  22.       return val.toString().toLowerCase().includes(_searchText);  
  23.     });  
  24.   
  25.   }  
  26. }  
In the above pipe implementation prop parameter is optional, you have to pass the key of object when you want to filter array of objects. Always make sure pure should be false in pipe metadata configuration. When your pipe pure value is false, Angular keeps on tracking every change detection, so even if you add a new item to your array you will get filtered items.
 
Example configuration
  1. Search : <input type="text" [(ngModel)]="searchText">  
  2. <br><br>  
  3. <table border="1">  
  4.   <tbody>  
  5.     <tr *ngFor="let item of data | tableFilter:searchText:'name'">  
  6.       <td>{{item.name}}</td>  
  7.       <td>{{item.price}}</td>  
  8.     </tr>  
  9.   </tbody>  
  10. </table>  
Stackblitz demo : https://angular-filter-demo.stackblitz.io
 
Let me know if you're facing any issue related to this.
 
Cheers!!