【问题标题】:Angular ngIf with array.indexOf only work once带有 array.indexOf 的 Angular ngIf 只能工作一次
【发布时间】:2020-02-09 16:10:30
【问题描述】:

我正在使用 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="isInCart(product)" 并在您的 ts 中:isIncart(product:any){return cart.find(x=> x.id == product.id)}

标签: angular ionic-framework ionic4 indexof angular-ng-if


【解决方案1】:

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

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

并将其绑定为,

 *ngIf=isFound(product)

【讨论】:

  • 我是这样应用的。 console.log(isFound(product)) 正确返回 true 或 false 但 ngIf 语句不起作用。 *ngIf="isFound(product)" 总是返回 true。
  • console.log(isFound(product)) 正确返回 true 或 false 但 ngIf 语句不起作用。 *ngIf="isFound(product)" 总是返回 true。
  • 我做到了。我打错了,我修复了它和它的作品。谢谢。
  • 我注意到将函数用作ngIf 条件时的有趣行为。显然,当在函数中读取观察到的变量(在你的情况下,它是product)并且函数(isFound)将被重复调用时,Angular 会检测到它们的变化。如果我在你那里,我会检查isFound 没有被调用超过必要的次数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多