-1

I have implemented custom pipe as below.

 @Pipe({
      name: 'search'
    })
    export class SearchPipe implements PipeTransform {

      transform(items: any[], searchText?: string): any {
        if (!items) return [];
        if (!searchText) return items;
        searchText = searchText.toLowerCase();
        return items.filter((item) => {
          return item.name.toLowerCase().includes(searchText);
        });
      }
}

here item.name is hard coded. so i want to pass key name dynamically along with searchText. so i can use it across application how to do it let me know.

Santhosh
  • 1,053
  • 1
  • 20
  • 45
  • 1
    Did you try adding another parameter, as you did with searchText? What's the specific problem you've had? – jonrsharpe Nov 20 '19 at 08:06
  • Possible duplicate of [How do I call an Angular 2 pipe with multiple arguments?](https://stackoverflow.com/questions/36816788/how-do-i-call-an-angular-2-pipe-with-multiple-arguments) – Sergey Mell Nov 20 '19 at 08:08

1 Answers1

0

Please try below code, i have added an extra parameter key.

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string, key?:string): any[] {
    if (!items) return [];
    if (!searchText) return items;
    searchText = searchText.toLowerCase();
    return items.filter(it => {
      if(!key){
        return it.toLowerCase().includes(searchText);
      } else {
        return it[key].toLowerCase().includes(searchText);
      }
    });
  }
}
akpgp
  • 761
  • 6
  • 10