角度 6 复选框过滤器



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

一个 porduct 是一个跟随 :

{
'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 

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

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

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

您不一定需要 NgModel 和两个绑定,您当然可以从数组动态生成过滤器,随着应用程序的增长,这可能是一个好主意。 您还可以使用可观察量,或创建一个管道来过滤 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

最新更新