我想使用复选框通过变量'category'过滤JSON对象(Products)列表。
一个产品是遵循:
{
'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和两个绑定,你当然可以从一个数组动态生成过滤器,这可能是一个好主意,因为你的应用程序增长。您也可以使用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)
);
}
}
MyComponent.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