typescript - Angular 6 复选框过滤器

标签 typescript checkbox angular6

我想使用复选框按变量“类别”过滤 JSON 对象(产品)列表。

产品如下:

  {
  'bikeId': 6,
  'bikeName': 'Kids blue bike',
  'bikeCode': 'KB-3075',
  'releaseDate': 'June 28, 2016',
  'description': 'Kids blue bike with stabalizers',
  'category': 'kids',
  'price': 290.00,
  'starRating': 4.8,
  'imageUrl': 'https://openclipart.org/image/2400px/svg_to_png/1772/bike-kid.png'
}

我当前的 ngFor 循环如下:
   <tr *ngFor="let product of products">
                       <td><img *ngIf='showImage' 
                         [src]='product.imageUrl' 
                        [title]='product.bikeName'
                        [style.width.px]='imageWidth'></td>
                       <td>{{product.bikeName}}</td>
                       <td>{{product.bikeCode}}</td>
                       <td>{{product.releaseDate}}</td>
                           <td>{{product.price}}</td>
                           <td>{{product.starRating}}</td>
</tr>

我当前的复选框如下:
 <input type="checkbox" name="All" value="true" /> Mens 
                <input type="checkbox" name="All" value="true" /> Womens 
                <input type="checkbox" name="All" value="true" /> Kids 

我问这个问题是因为我整天搜索论坛无济于事。一些答案确实回答了它,但是当我测试代码时,它要么已经过时,要么就是不起作用。任何帮助,将不胜感激。

最佳答案

很惊讶你在网上找不到一个例子,因为有很多方法可以解决这个问题,我的答案只是一个。

在此示例中,我保持产品来源不变,但创建第二个数组,其中包含显示的产品。我将每个复选框绑定(bind)到过滤器模型的属性,当发生更改时,我调用 filterChange()从该模型更新我的过滤产品数组。

您不一定需要 NgModel 和两个绑定(bind),并且您当然可以从数组中动态生成过滤器,随着您的应用程序的增长,这可能是一个好主意。你也可以使用 Observables,或者创建一个 Pipe 来过滤 NgFor 中的数组。真的,可能性是无穷无尽的。

MyComponent.ts

export class MyComponent {
  filter = { mens: true, womens: true, kids: true };
  products: Product[] = []
  filteredProducts = Product[] = [];

  filterChange() {
    this.filteredProducts = this.products.filter(x => 
       (x.category === 'kids' && this.filter.kids)
       || (x.category === 'mens' && this.filter.mens)
       || (x.category === 'womens' && this.filter.womens)
    );
  }
}

我的组件.html
<tr *ngFor="let product of filteredProducts"> <!-- ... --> </tr>
<!-- ... --->
<input type="checkbox" [(ngModel)]="filter.mens" (ngModelChange)="filterChange()" /> Mens 
<input type="checkbox" [(ngModel)]="filter.womens" (ngModelChange)="filterChange()" /> Womens 
<input type="checkbox" [(ngModel)]="filter.kids" (ngModelChange)="filterChange()" /> Kids

关于typescript - Angular 6 复选框过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52725392/

相关文章:

javascript - Angular 2/4/Universal - 如何使用 JSON-LD 数据?

typescript - 类型错误 : Class constructor MixinStrategy cannot be invoked without 'new'

android - 如何使用复选框创建 ListPreference

css - 如何在 angular.json 的 lazyload css 中添加哈希

javascript - 我是否必须显式清理 Angular 6 中的输入字段?

javascript - 让 TypeScript 知道在运行时通过 mixin 添加到对象的方法

angular - 为什么要编译 Angular

css - checkbox-inline 将复选框放在文本上而不是旁边

javascript - 检查是否检查了子输入

javascript - 如何仅使用 Angular6 在单击的按钮上设置事件类?