0
votes

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

2

2 Answers

0
votes

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

0
votes

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'