首页 > 解决方案 > 如何根据单击的复选框更新视图?

问题描述

我正在尝试使用 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>

标签: angularangular-changedetection

解决方案


在您的示例代码中,您似乎从未清除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


推荐阅读