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);
- });
-
- }
- }
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
- 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!!