Angular 2复选框过滤

时间:2018-03-07 19:34:24

标签: angular checkbox angular-pipe array-filter

我希望使用Angular 2过滤多个复选框,并实现类似THIS的内容 问题是当我检查2个不同的复选框时,应用程序无法正常工作。

App.Component.html

from django.forms import modelformset_factory


class ItemListView(ListView):
    model = Item

    def get_context_data(self, **kwargs):
        data = super(ItemListView, self).get_context_data()
        formset = modelformset_factory(Item, form=ItemForm)()
        data['formset'] = formset
        return data

App.Component.ts

    <div  *ngFor="let s of cpuName">
      <input  type="checkbox" [(ngModel)]="s.checked" (click)="updateFilter(s)"  >{{s.name}}
    </div>

    <div  *ngFor="let n of cpuCode">
      <input  type="checkbox" [(ngModel)]="n.checked" (click)="updateFilter(n)"  >{{n.name}}
    </div>

  <ul>
      <div *ngFor="let a of allCpu | filterPipe: filterArr">
          ID: {{a.id}}, Name: {{a.name}}, Code: {{a.code}}
      </div>
  </ul>

Pipe.ts

export class AppComponent {
  filterArr = [];
  cpuName = [{checked:false,name:'Intel'},{checked:false,name:'AMD'}]
  cpuCode =[{checked:false,name:'i5'},{checked:false,name:'i7'},{checked:false,name:'ryzen7'}]
  name:string;

  allCpu = [
    {id:1, name:'Intel', code:'i5'},
    {id:2, name:'Intel', code:'i5'},
    {id:3, name:'AMD', code:'ryzen7'},
    {id:4, name:'Intel', code:'i7'},
    {id:5, name:'AMD', code:'ryzen7'},
    {id:6, name:'Intel', code:'i7'}
  ]


  updateFilter(option) {
    if(!option.checked) {
      this.filterArr.push(option.name);
      console.log(this.filterArr);
    }
    else {
      let index = this.filterArr.indexOf(option.name);
      this.filterArr.splice(index, 1);
    }
  }
}

这是Final Output

GITHUB PROJECT

1 个答案:

答案 0 :(得分:0)

你几乎可以开始工作了。

i5,i7是你的allCpu中的代码,你需要在迭代项检查名称或代码时修改你的管道

item有2个属性:名称和代码。

您的Intel和AMD过滤器有效,因为您检查args是否包含项目名称。

 transform(value: any, args?: any[]): any {
   let result = value.filter( item => args.indexOf(item.name) > -1);
   result = value.filter(item => args.indexOf(item.code) > -1);
   return result;
 }