Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter pipe Angular - Multiple parameters

I have my pipe filter that receives an object defined in the html, only that I have to define the attributes that it will filter. how can I generate my filter without having to pass the parameters of the html?. I would like you to filter all the columns in general.

HTML----

<tr *ngFor="let view of list | filter : { id:searchText, name:searchText, 
   age:searchText }">

   <td>{{view.id}}</td>
   <td>{{view.name}}</td>
   <td>{{view.age}}</td>
</tr>



PIPE---

export class FilterPipe implements PipeTransform {
      transform(value: any, searchText: any): any {
      let filterKeys = Object.keys(searchText);

      return value.filter(item => {
        return filterKeys.some((keyName) => {
          return new RegExp(searchText[keyName], 'gi').test(item[keyName]);
       });
     });
  }
 }
like image 313
George Avatar asked Mar 06 '26 19:03

George


1 Answers

I did this example in wich you dont need to pass the object properties to the filter: https://stackblitz.com/edit/angular-zmzyy9

The pipe looks like:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'filterAll' })
export class FilterPipe implements PipeTransform {
  transform(value: any, searchText: any): any {
    if(!searchText) {
      return value;
    }
    return value.filter((data) => this.matchValue(data,searchText)); 
  }

 matchValue(data, value) {
   return Object.keys(data).map((key) => {
       return new RegExp(value, 'gi').test(data[key]);
   }).some(result => result);
 }
}

And used in the HTML:

<tr *ngFor="let view of list | filterAll: searchText">
    <td>{{view.id}}</td>
    <td>{{view.name}}</td>
    <td>{{view.age}}</td>
</tr>
like image 138
Daniel Caldera Avatar answered Mar 08 '26 09:03

Daniel Caldera