angular - 如何根据单击的复选框更新视图?
问题描述
我正在尝试使用 json 对象为不同的产品实现过滤器。
预期输出:我需要单击过滤器复选框时,产品列表应缩小为过滤后的产品
实际输出:将过滤后的产品添加到现有产品列表中
我已经编写了过滤产品的逻辑,它正在被过滤,但是在更新 View 时它被添加到现有的产品列表中。
```/*---Service call for fetching category details by passing categoryId--- */
----Type Script code----
getCategoryDetailsById(categoryId: Number) {
this.categoryService.getCategoryDetailsById(categoryId).subscribe(resp => {
this.categorySearchDetails = resp as CategorySearchDetails;
this.categorySearchDetails.products.forEach(products => {
products.images.forEach(images => {
if (images.imageType === "productMainImage") {
this.mainImgList.push(images.imageURL)
}
else if (images.imageType === "productHoverImage") {
this.hoverImgList.push(images.imageURL)
}
})
});
});
}
/*---iterating list from json object when check box is clicked--- */
onToggle(event: any) {
this.categorySearchDetails.products.forEach(resp => {
resp.productCategoryAttribute.forEach(resp1 => {
this.attributeValue = resp1.categoryAttributeValues[0].value
resp.images.filter(element => {
if (element.productId === resp.productId && event === this.attributeValue) {
if (element.imageType === "productMainImage") {
this.mainImgList.push(element.imageURL);
}
else if (element.imageType === "productHoverImage") {
this.hoverImgList.push(element.imageURL)
)
}
}
});
});
});
}
-----Html Code-------
<ng-container *ngFor="let filters of filtersList">
<div class="breakLine">
<mat-checkbox *ngFor="let values of filters.categoryAttributeValues"(change)="onToggle(values.attributeValue)">{{values.attributeValue}}<br/>
</mat-checkbox>
</div> <br>
</ng-container>
<!-- Dynamic Product Grid -->
<form >
<div class="col-md-3 col-sm-12 col-xl-3"*ngFor="let mainImage of mainImgList;let i=index; ">
<div routerLink="/product/{{productId[i]}}">
<img class="pic-1" [src]="mainImage">
<img class="pic-2" [src]="hoverImgList[i]">
</div>
</div>
</form>
解决方案
在您的示例代码中,您似乎从未清除mainImgList
过。
一种方法是为filteredImgList
和创建单独的变量mainImgList
。
最初,filteredImgList
将包含mainImgList
. 在过滤器点击时,filteredImgList
需要清除,然后重新查询mainImgList
以找出有效的图像。
/*---Service call for fetching category details by passing categoryId--- */
this.mainImgList = [];
this.filteredImgList= [];
//after service call in subscribe method
this.filteredImgList = this.mainImgList;
//after toggle
this.filteredImgList = this.mainImgList.filter(()=> /*some condition*/);
并将您的 html 绑定filteredImgList
到
推荐阅读
- rest - 无法在 Spring Boot 中公开端点以接收来自 Google 的授权代码
- c# - 从分组的dataTable c#中获取项目
- sql-server - 仅检查字符串中存在的特定字段
- regex - Flex-lexer 如何匹配简单的语句?
- java - 在不同的按钮点击时显示相同的广告
- python - 无法使用 cron 运行 python 脚本
- apache-spark - 排序后如何从数据集中仅选择特定列
- c# - 为什么在这个循环中,while 条件被忽略为 n-1 值?
- c# - 右键单击系统托盘中的通知图标不显示上下文菜单
- reactjs - 连续成功触发两个 useReducer 钩子