Olivier
Olivier

Reputation: 3400

How to pass array as arg in Pipe in Angular2

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 :/

Upvotes: 7

Views: 6036

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202216

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

Upvotes: 10

Related Questions