How to use multiple checkbox to filter data in Angular 2
Asked Answered
E

0

6

I'm creating a filter page with Angular 2. The data is being filtered depending on the checkboxes that are checked.

This is the HTML

    <input required type="checkbox" name="checkbox" value="value1" (change)="toggleFilter(kind.value)" #kind/>
    Filter option 1

    <input required type="checkbox" name="checkbox" value="value2" (change)="toggleFilter(kind2.value)" #kind2 />
    Filter option 2

    <input required type="checkbox" name="checkbox" value="value3" (change)="toggleFilter(kind3.value)" #kind3 />
    Filter option 3


<div *ngFor="let item of (items | FilterPipe: filterFormat)">
    {{item.id}} {{item-title}}
</div>

This is a piece of my Item component. In the toggleFilter() i'm population the array filterOptions with the values of the checkbox. The get filterFormat() returns the populated array and places it as an argument in the Filterpipe (which is located in the HTML)

filterOptions: [] = [];

toggleFilter(value: any) {

    let index = this.filterOptions.indexOf(value);

    if (index > -1) {
      this.filterOptions.splice(index, 1);
    } else {
      this.filterOptions.push(value);
    }

    return this.filterOptions;
}

get filterFormat() {
   console.log('call filterFormat');
   return this.filterOptions.map(res => res);
}

How can I use the checkboxes as pipe arguments in able to filter the data?

Esbensen answered 13/9, 2016 at 7:29 Comment(2)
Do you still need help with this question?Negron
The real question is why are you implementing it as a pipe? This is not a job for the pipe. Do the logic inside a service or at least in your component's code.Delorisdelorme

© 2022 - 2024 — McMap. All rights reserved.