0

i am trying to make a flexible pipe to filter my array of objects to display it with *ngFor

<div class="wrapper" *ngFor="let item of items | myFilter:property:true">

for example i want to show div only for object with true property :

[
{'name':'first', 'property': 'true'}, 
{'name':'last', 'property': 'false'}
]

It seems not to work when i try to set property dynamically like this

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

@Pipe({
name: 'myFilter'
})
export class FilterPipe implements PipeTransform {
     transform(items: any[], key: any, value: any): any {
         return items.filter(item => item[key] === value ? item : null);
     }
}

I tried also this

item['"' + key + '"']

and this (with es6 template strings)

item[`"$key"`]

but this pipe works well if i call property straight like this

item.property

And i really need to make it more flexible, because i have a lot of situations in my app where i need to filter items by different properties values

  • Check this out: http://stackoverflow.com/questions/41672578/filter-on-multiple-columns-using-one-pipe-angular-2/41841674#41841674 – seidme May 18 '17 at 14:01

2 Answers2

0

Array.filter expects your filter function to return a boolean, meaning that you should change your filter for this:

transform(items: any[], key: any, value: any): any {
     return items.filter(item => item[key] === value);
 }

Source: MDN

Supamiu
  • 8,501
  • 7
  • 42
  • 76
  • thx for correction, but it still not work. As i said, it was working with straight property calling – Oleg Burdasov May 18 '17 at 13:56
  • you should probably check if item[property] exists using a console.log just before the return (check with console.log(items[0][property])) – Supamiu May 18 '17 at 13:59
0

Your pipe is definitely correct, you are just missing the '' on your HTML. Try to call it like this: <div class="wrapper" *ngFor="let item of items | myFilter:'property':true"> and it will work perfectly. This is because the pipe expects a string, but you are giving an object reference. property != 'property'

Gianluca Paris
  • 1,391
  • 1
  • 14
  • 25