嗨,我是角色的新手,我正在尝试创建一个anuglar复选框过滤器管道来过滤我的产品数据!这里我已经为我的.ts文件中的复选框创建了一种颜色(我没有包含代码而不是与此问题相关)
public colors: any[] = [
{
id: 1,
color: "Black",
selected: true,
},
{
id: 2,
color: "Green",
selected: true,
}
]
我正在使用管道进行复选框 -
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'selectBrand'
})
export class SelectBrandPipe implements PipeTransform {
transform(check: any, checked?: any): any {
console.log('checked', checked);
return checked ? check.filter(sal => sal.type === checked) : check;
}
}
在我的HTML文件中 -
<form>
<div class="form-check brand-checkbox" *ngFor="let col of colors">
<input class="form-check-input"
type="checkbox"
value="{{col.id}}"
id="{{col.id}}"
name=""
[(ngModel)]="col.selected">
<label class="form-check-label" for="{{col.id}}">
{{col.productColor}}
</label>
</div>
</form>
<div class="shop" *ngFor="let prod of productListShow">
<div class="col-md-4" *ngFor="let product of prod.product | selectBrand: colors">
<h5>{{product.productName}}</h5>
</div>
</div>
我从服务中获取产品数据 -
{
id: 1,
productName:'Products',
product: [
{
productId: 1,
productName: 'Shirt 1',
productColor: 'Green',
},
{
productId: 2,
productName: 'Shirt 2',
productColor: 'Black',
},
],
},
当代码运行时,所有选中的复选框都被选中,我在控制台日志中看不到任何产品。我到了 -
checked
(2) [{…}, {…}]
0
:
{id: 1, productColor: "Black", selected: true}
1
:
{id: 2, productColor: "Green", selected: true}
length
:
2
__proto__
:
Array(0)
答案 0 :(得分:1)
您将产品数组传递为检查,并将数组颜色为已检查到您的pipeTransform函数中。然后检查product.type(根据您的产品型号定义不存在btw)是否等于颜色Array。我想这不是你要检查的内容。
尝试:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'selectBrand',
pure: false
})
export class SelectBrandPipe implements PipeTransform {
transform(products: any[], colors: any[]): any {
const activeColors = colors.filter(c => c.selected).map(c => c.color)
console.log('checked colors', activeColors.join(","));
return products.filter(p => activeColors.includes(p.productColor));
}
}
顺便说一句:如果您真的想使用管道进行过滤,则需要一个不纯的管道,由于性能原因,不推荐使用。
我建议仅在用户通过向复选框input-element添加(ngModelChange)来更改复选框状态时过滤产品,例如:
<input class="form-check-input"
type="checkbox"
value="{{col.id}}"
id="{{col.id}}"
name=""
[(ngModel)]="col.selected"
(ngModelChange)="filterProducts()">
在你的组件打字稿中添加一个函数filterProducts来进行过滤:
public filterProducts(): void {
const filteredProductArray = new Array<any>();
const activeColors = this.colors.filter(c => c.selected).map(c => c.color);
this.productListShow.forEach(prod => {
const filteredSubProducts = prod.product.filter(p => activeColors.includes(p.productColor));
if(filteredSubProducts.length > 0){
const clonedProduct = Object.assign({}, prod);
clonedProduct.product = filteredSubProducts;
filteredProductArray.push(clonedProduct);
}
});
this.filteredProducts = filteredProductArray;
}
然后在ngFor中使用filteredProducts而不是productListShow
答案 1 :(得分:0)
Checkbox的NgModel:
<input id="colId{{i}}" [checked]="col.active" class="" (change)=" col.active = !col.active" type="checkbox">
<label for="colId{{i}}" ></label>