Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass array as arg in Pipe in Angular2

Tags:

angular

I have created a Pipe which purpose is to filter a list depending on a list of tags.

@Pipe({
  name: "tagfilter"
})
export class TagFilterPipe implements PipeTransform {
    transform(items: Event[], args: any[]) :any {
    if (args.length === 0) {
      return items;
    }
    return _.filter(items, (item: any) => {
            return (_.intersection(item.tags, args[0]).length > 0)
        });
    }
}

I am then using it like this :

<tbody class="myline" *ngFor="#event of chapter.events | tagfilter:selectedTags" [event]="event">

However, "selectedTags" is an array of strings and if I add or remove entries from this array, it does not trigger the filter and so, my list is not filtered :/

like image 897
Olivier Avatar asked Jan 28 '16 15:01

Olivier


People also ask

How do you pass parameters to a pipe MyPipe?

In your component's template you can use multiple arguments by separating them with colons: {{ myData | myPipe: 'arg1':'arg2':'arg3'... }} Pipes take an array that contains all arguments, so you need to call them like this: new MyPipe().

What is parameterized pipe in angular?

In an angular application, when we pass any parameters to the pipes, it is called parameterized pipes we can pass n number of parameters to pipes using a colon (:).


1 Answers

I think that it's how change detection works in Angular2. I mean updates within objects don't trigger change detection but if you update the whole reference, it does.

To reevaluate the pipe, you need to replace the array with a new one:

@Component({
  selector: 'my-app', 
  template: `
    <div>
      <span *ngFor="#l of (list | sort:excluded)">{{l}}</span>
    </div>
    <div (click)="updateArgs()">Update args</div>
  `,
  pipes: [ SortPipe ]
})
export class AppComponent {
  constructor() {
    this.list = [ 'n', 'g', 'a', 'u', 'r', 'l' ];
  }

  updateArgs(array) {
    this.excluded = [ 'n', 'g' ];
  }
}

In my sample, when executing updateArgs, the transform method of the pipe is called again.

Here is a plunkr: https://plnkr.co/edit/GWcEOeY0koXZ5vroRntV?p=preview.

Hope it helps you, Thierry

like image 50
Thierry Templier Avatar answered Oct 01 '22 18:10

Thierry Templier