Issue
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
You can not use what-ever() => {..}
in .html. (this is the error that Angular shows)
You have two approaches:
- 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) }}
- In your
this.auth.cart
array items, add a new property "inCart" and manually set this property totrue
whenever the user adds the item to cart and tofalse
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;
}
Answered By - Eliseo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.