Angular ngIf 和 array.indexOf 只工作一次

Angular ngIf with array.indexOf only work once

我正在使用 ionic 4 开发商店应用程序。我试图在每个产品下显示添加到购物车按钮或加号、减号图标。

如果商品不在购物车中显示添加按钮 (1)

<div id="add{{ product.id }}" *ngIf="cart.indexOf(product) < 0" (click)="addToCart(product)"><div class="addtoCart"><ion-icon name="md-cart"></ion-icon></div></div>

如果商品在购物车中显示计数、加号、减号图标 (2)

<div id="count{{ product.id }}" *ngIf="cart.indexOf(product) >= 0" style="float: left;width: 50%;">
    <div (click)="decreaseProduct(product)" style="color: #f0ab16;float: left;width: 40%;text-align: center;"><ion-icon name="md-remove-circle-outline"></ion-icon></div>
    <div style="width: 20%;float: left;text-align: center;font-size: 12px" >{{ cart[cart.indexOf(product)].amount }}</div>
    <div (click)="addToCart(product)" style="float: left;width: 40%;text-align: center; color: #f0ab16"><ion-icon name="md-add-circle-outline"></ion-icon></div>
    </div>

此代码效果很好,但是当我更改选项卡并返回此页面时,ngIf 语句不起作用。它卡在添加到购物车 (1) 按钮上,但我的商品仍留在购物车中。添加到购物车按钮仍然有效。

我认为 *ngIf="cart.indexOf(product) >= 0" 只能工作一次。我怎样才能使它正常工作。

总是更喜欢在自定义函数中使用 *ngIf 条件而不是在模板上执行,您可能需要创建一个自定义函数,其中 returns 一个布尔值,

isFound(product:any){
  return cart.find(x=> x.id == product.id);
}

并将其绑定为,

 *ngIf=isFound(product)