Kyle Valderrama
Kyle Valderrama

Reputation: 31

Is there a way to pass an array argument to a pipe?

Is there some way to pass an array argument to a pipe?

i've done a code like this:

<div *ngFor="let List of Lists | customPipe: [1,2,3]">
 <div>{{List.name}}</div>
</div>

and doesn't seem to work.

However, if i did customPipe:[1] it works with only 1 value inside the array

Here is my pipe code:

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

@Pipe({
  name: 'customPipe',
  pure: false
})
export class PettypePipe implements PipeTransform {

transform(Lists: any[], args: number[]): any{

    if(!args)return petType;

    return (Lists||[]).filter(l=> l.id == args); 

  }

}

Upvotes: 2

Views: 925

Answers (1)

Khanji
Khanji

Reputation: 158

So it seems what you want to accomplish is to filter the array with a pipe, showing the exact items stated as the argument of the pipe.

Your args is an array of numbers, and you filter once where the id has to equal the array of numbers. I think what you mean to do is to find any item with an id equal to any number in the args. To accomplish that, you could simply do:

transform(Lists: any[], args: number[]): any {
  return (Lists||[]).filter(l => args.includes(l.id));
}

This will return all the items that include the id specified in the args array. To make it optional to give an array or just a number, you could enhance the code to look something like this:

transform(Lists: any[], args: number|number[]): any {
  return (Lists||[]).filter(l => {
      if(isNaN(args)){
        return args.includes(l.id);
      } else {
        return l.id === args;
      }
    });
}

So to answer your question: Is there a way to pass an array argument to a pipe? Yes, but your pipe has to handle the array the right way.

Upvotes: 1

Related Questions