如何从 Angular 视图中的对象数组中查找特定 ID

How to find a specific ID from an Array of Objects in Angular View

我正在建立一个购物网站,我想将按钮文本从 'Add to cart' 切换到 'In Cart'

cart 数组在 auth 提供程序中设置,因此它可以在所有组件中访问。

<button *ngIf="auth.isLoggedIn" (click)="addToCart()" class="button button-add-to-cart">
 <i class="fal fa-shopping-cart"></i>
  {{(auth.cart.length && (auth.cart[0].product._id == product.list[0]._id)) ? 'In Cart' : 'Add to Cart'}}
</button>

如果我使用上面的代码,那么我可以将产品与购物车数组的第一个元素进行比较,无论它是否在购物车中,并且它工作正常(当产品在购物车中时它显示在购物车中)。

但问题是购物车有多个项目。

当我添加多个项目时,它不起作用。我使用了 find 方法 Like this

{{(auth.cart.length && (auth.cart.find(x => x.product._id == product.list[0]._id) == product.list[0]._id)) ? 'In Cart' : 'Add to Cart'}}

但是显示如下错误

Parser Error: Bindings cannot contain assignments at column 41 in [ {{(auth.cart.length && (auth.cart.find(x => x.product._id == product.list[0]._id) == product.list[0]._id)) ? 'In Cart' : 'Add to Cart'}} ]

那么我可以从购物车数组中找到特定的 ID 吗?

我需要它来自 Angular View(html) 而不是来自 .ts 文件

如有任何帮助,我们将不胜感激。谢谢

您不能在 .html 中使用 what-ever() => {..}。 (这是 Angular 显示的错误)

你有两种方法:

  1. 使用 .ts 中的函数
    getInCart(productId:any) => {
        return this.auth.cart && this.auth.cart.find(x=>x.product._id==productId)
          ? 'in cart' : 'add to cart'
    }

在你的.html

    {{ getInCart(product._id) }}
  1. 在您的 this.auth.cart 数组项目中,添加一个新的 属性“inCart”,并在用户将项目添加到购物车时手动将此 属性 设置为 true 并且到 false 当用户删除它时。

第一种方法的优点是更改最少。 “成本”是 较低的性能 (请记住,当您将函数放入 .html 时,它会在每个检测周期执行 - 如果您有鼠标移动,这可能很关键) .

注意:另一种方法是使用模板引用变量,使用 ViewChildren 并询问具有特定属性的 nativeElement - 但我想这不是你要找的。

<div #element [id]="'product' + i">
@ViewChildren('element') elements: QueryList<ElementRef>

findElement(productId) {
    const element = this.elements.find(x=> 
        x.nativeElement.getAttribute('id') == productId)
    // element only gives you the ElementRef
    // without reference to your array
    return element;
}