2016-02-15 55 views
2

我想弄清楚如何使用Angular和Pipes構建產品的實時過濾器。在我的HTML我有這個循環的產品:在Angular 2中使用管道過濾複選框

<div *ngFor="#product of products | filter"> 
    <div class="product">{{product.id}}</div> 
</div> 

看來,我可以通過輸入濾波器參數添加到過濾器功能:說法,我不知道是我怎麼能添加含有從該值的參數輸入字段在頁面上。我想要改變過濾器中的內容,具體取決於是否檢查是否有

<input type="checkbox"> 

。我怎麼做?

回答

2

使用本地模板變量:

<input #ref type="checkbox"> 

值傳遞給你的過濾器:

<div *ngFor="#product of products | filter: ref.checked"> 
    <div class="product">{{product.id}}</div> 
</div> 
+0

我想你想'ref.checked'。 –

+0

更正,謝謝! – pixelbits

+0

我喜歡這個解決方案!關於進一步的問題:如何在更改複選框時觸發過濾器? – theva

2

傳遞使用NgModel綁定到複選框組件屬性:

@Pipe({name: 'filter'}) 
export class FilterPipe implements PipeTransform { 
    transform(products, args:string[]) : any { 
    return products.filter(product => { 
     if(args[0]) { 
     return product.id > 1; 
     } 
     return product.id; 
    } 
    } 
} 

@Component({ 
    selector: 'my-app', 
    pipes: [FilterPipe], 
    template: ` 
    <div *ngFor="#product of products | filter:enableFilter"> 
    <div class="product">{{product.id}}</div> 
    </div> 
    <input type="checkbox" [(ngModel)]="enableFilter"> enable filter 
    <p>{{enableFilter}}` 
}) 
export class AppComponent { 
    enableFilter = false; 
    products = [{id:1}, {id:2}, {id:3}]; 
    constructor() { console.clear(); } 
} 

Plunker

如果組件邏輯中沒有需要知道複選框的值,我喜歡@pixelbits的答案。

2

你也可以用你的腳本代碼來做到這一點。 例子:

使命名的產品和方法,一個空數組進行此項操作:

products: any = []; 

     onCheck(value){ 

    if(this.locations.includes(value)){ 
     let index = this.locations.indexOf(value); 
     this.locations.splice(index,1); 
     console.log(this.locations);  
    } 
else{ 
    this.locations.push(value); 
    console.log(this.locations); 
}  
    } 
在HTML

<input type="checkbox" name="product" value="burger" #burger (change)="onCheck(burger.value)"> 

    <input type="checkbox" name="product" value="pizza" #pizza (change)="onCheck(pizza.value)"> 

Eventhough,它是痘痘有點長,但它會使事情變得簡單了過濾工作