使用Angular 2中的管道在复选框上进行过滤

使用Angular 2中的管道在复选框上进行过滤,angular,Angular,我正试图弄明白如何使用角度和管道构建产品的实时过滤器。在我的html中,我有以下产品循环: <div *ngFor="#product of products | filter"> <div class="product">{{product.id}}</div> </div> {{product.id} 似乎我可以通过键入filter:argument向filter函数添加参数,我想知道的是如何添加包含页面上输入字段值的参数。我想更

我正试图弄明白如何使用角度和管道构建产品的实时过滤器。在我的html中,我有以下产品循环:

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

{{product.id}
似乎我可以通过键入filter:argument向filter函数添加参数,我想知道的是如何添加包含页面上输入字段值的参数。我想更改过滤器中的内容,具体取决于

<input type="checkbox"> 


是否检查。如何执行此操作?

使用本地模板变量:

<input #ref type="checkbox">

将值传递给过滤器:

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

{{product.id}

使用
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(); }
}
@Pipe({name:'filter'})
导出类FilterPipe实现PipeTransform{
转换(产品,参数:字符串[]):任意{
返回产品。过滤器(产品=>{
如果(参数[0]){
返回产品id>1;
}
返回产品id;
}
}
}
@组成部分({
选择器:“我的应用程序”,
管道:[过滤器管道],
模板:`
{{product.id}
启用过滤器
{{enableFilter}}`
})
导出类AppComponent{
enableFilter=false;
产品=[{id:1},{id:2},{id:3}];
构造函数(){console.clear();}
}


如果组件逻辑中没有任何内容需要知道复选框的值,我喜欢@pixelbits的答案。

您也可以使用您的typescript代码来完成这项工作。 例如:

为此操作创建一个名为products和method的空数组:

  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)">


尽管它有点长,但它会使过滤工作变得容易

我想你想要
ref.checked
。我喜欢这个解决方案!关于进一步的问题:如何在更改复选框时触发过滤器?在管道声明中指定pure:false