首页 > 解决方案 > 产品折扣显示和隐藏Angular中的错误

问题描述

我只想在折扣百分比大于 0 时才显示折扣百分比和原始价格(删除)。我从服务器动态获取这两个值,因为我使用 ngFor 循环。我只是将它绑定到我的 html 中。为了实现这一点,我使用了 *ngIf 指令。但即使它为零,它也会显示所有折扣值。如何使用 ngIf 来实现这一点。任何人都可以帮助解决这个问题。在此先感谢..我不想显示 0% 的折扣以及删除价格。

我的 component.html 是:

<div *ngIf="discountPercent!==0">
    <div class="col-md-3" *ngFor="let product of productList">
      <figure class="card card-product"> 
        <div class="starburst discount" id="star" #rotateEl>
          <span></span>
          <span>{{product.Discount}}%</span>
        </div>
        <div class="img-wrap">
       <a routerLink="/product-details"><img src="assets/{{ product.Image }}"></a>  
        </div>
        <div class="parent">
        <div class="block-ellipsis">
          <span>{{product.ProductName}}</span>
        </div>
      </div>
        <div class="bottom-wrap">
          <div class="price-wrap h5">
            <span class="price-new">Rs.{{product.DiscountedPrice}}</span> &nbsp;
            <del class="price-old">Rs.{{product.OriginalPrice}}</del>
          </div>
        </div>
      </figure>
    </div>
  </div>

我的 component.ts 文件是:

export class ProductsComponent implements OnInit {
    discountPercent = 0;
     ngOnInit() {
        this.productsService.getProducts()
        .then((response:Response) => {
          console.log(response);
          this.productList = response;
          this.discountPercent = this.productList.Discount;
        })
        .catch(err => console.log(err));
      }
}

标签: angular

解决方案


看起来discountPercent变量是没有必要的。试试这个。

<div class="col-md-3" *ngFor="let product of productList">
  <figure class="card card-product"> 
    <div *ngIf="product.Discount" class="starburst discount" id="star" #rotateEl>
      <span></span>
      <span>{{product.Discount}}%</span>
    </div>
    <div class="img-wrap">
   <a routerLink="/product-details"><img src="assets/{{ product.Image }}"></a>  
    </div>
    <div class="parent">
    <div class="block-ellipsis">
      <span>{{product.ProductName}}</span>
    </div>
  </div>
    <div class="bottom-wrap">
      <div class="price-wrap h5">
        <span class="price-new">Rs.{{product.DiscountedPrice}}</span> &nbsp;
        <del *ngIf="product.Discount" class="price-old">Rs.{{product.OriginalPrice}}</del>
      </div>
    </div>
  </figure>
</div>

推荐阅读