0
votes

I'm having a problem using a pipe with multiple filters in Angular2.

This is my html:

<div class="container">
  <div class="row">
    <filters (onSelectedCategoryChange)="changeSelectedCategory($event)" (onSelectedTypeChange)="changeSelectedType($event)"></filters>
  </div>
  <br />
  <div class="row">
    <place *ngFor="let place of (places | placeSearch: selectedCategory : selectedType)" [place]="place"></place>
  </div>
</div>

Place and filters being both components contained in the same module.

This is the pipe:

import { Place } from './../../shared/models/place';
import { Pipe, PipeTransform } from '@angular/core';

import * as _ from 'underscore';

@Pipe({
    name: 'placeSearch'
})
export class PlaceSearchPipe implements PipeTransform {

    constructor() { }

    transform(places: Place[], args: string, typeFilter: string): any {
        if (args) {
            places = _.filter(places, function (place) {
                return place.categories.indexOf(args) !== -1;
            });
        }

        if (typeFilter) {
            places = _.filter(places, function (place) {
                return place.type === typeFilter;
            });
        }

        return places;
    }
}

What's happening is, when the page loads with all the elements of the array, everything's ok, then I apply one on the filters, and it filters correctly. But then when I undo the filter and apply another one (that affects other elements not contained in the first set of filter), only items contained in the first set of filter that also would be in this filter remain.

1

1 Answers

0
votes

I found out why it wasn't working. It was because of this:

<place *ngFor="let place of (places | placeSearch: selectedCategory : selectedType)" [place]="place"></place>

When I changed it to:

<div *ngFor="let place of places | placeSearch: selectedCategory : selectedType">
  <place [place]="place"></place>
</div>

it started working.