3

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

1 Answer 1

5

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.