5 checkbox typescript 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'
}
Run Code Online (Sandbox Code Playgroud)
我目前的 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>
Run Code Online (Sandbox Code Playgroud)
我当前的复选框如下:
<input type="checkbox" name="All" value="true" /> Mens
<input type="checkbox" name="All" value="true" /> Womens
<input type="checkbox" name="All" value="true" /> Kids
Run Code Online (Sandbox Code Playgroud)
我问这个问题是因为我整天都在搜索论坛无济于事。有些答案确实回答了它,但是当我测试代码时,它要么已经过时,要么就是无法正常工作。任何帮助,将不胜感激。
很惊讶您在网上找不到示例,因为有很多方法可以解决这个问题,而我的答案只是其中一种。
在此示例中,我保持产品源不变,但创建第二个数组,其中将包含显示的产品。我将每个复选框绑定到过滤器模型的属性,当发生更改时,我调用filterChange()以更新该模型中的过滤产品数组。
您不一定需要 NgModel 和两个绑定,并且您当然可以从数组动态生成过滤器,随着应用程序的增长,这可能是一个好主意。您还可以使用 Observables,或者创建一个 Pipe 来过滤 NgFor 中的数组。确实,可能性是无限的。
我的组件.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)
);
}
}
Run Code Online (Sandbox Code Playgroud)
我的组件.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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7045 次 |
| 最近记录: |