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

I am building a shopping site and I want to switch a button Text from 'Add to cart' to 'In Cart'

cart array is set in auth provider so it's accessible in all components.

<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>

If I use above code then i can compare a product with the first element of the cart array wheather its in the cart or not, and it's working fine (when a product is in cart its showing In Cart).

But the problem is Cart has multiple item.

When I add multiple item it will not work. I have used find method 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'}}

But it's showing below error

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'}} ]

So Can I find that specific id from cart array ?

I need it from Angular View(html) not from .ts file

Any help would be highly appreciated. Thank You



Solution 1:[1]

You can not use what-ever() => {..} in .html. (this is the error that Angular shows)

You have two approaches:

  1. Use a function in .ts
    getInCart(productId:any) => {
        return this.auth.cart && this.auth.cart.find(x=>x.product._id==productId)
          ? 'in cart' : 'add to cart'
    }

And in your .html

    {{ getInCart(product._id) }}
  1. In your this.auth.cart array items, add a new property "inCart" and manually set this property to true whenever the user adds the item to cart and to false when the user removes it.

The first approach has the advantage of minimal changes. The "cost" is less performance (remember that when you put a function in .html this is executed for each detection cycle - if you have a mousemove this can be critical).

NOTE: Another approach is using a template reference variable, use ViewChildren and ask about the nativeElement with a certain attribute - but I imagine that this is not what are you looking for.

<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;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Octavian Mărculescu