0

I'm developing store application with ionic 4. I am trying to show add to cart button or plus, minus icons under the every single product.

If item is not in the cart show add button (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>

If item is in the cart show count, plus, minus icons (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>

This codes works great, but when I changed tabs and get back this page ngIf statement doesnt work. Its stuck on add to cart(1) button but my items still stay in cart. Add to cart button still works too.

I think *ngIf="cart.indexOf(product) >= 0" only work once. How can i make this work properly.

1
  • 1
    Why dont you make a function? *ngIf="isInCart(product)" and in your ts: isIncart(product:any){return cart.find(x=> x.id == product.id)} Commented Feb 9, 2020 at 16:15

1 Answer 1

1

It's always prefer to use the *ngIf condition within a custom function rather than getting executed on the template, you might need to create a custom function which returns a Boolean value,

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

and bind it as,

 *ngIf=isFound(product)
Sign up to request clarification or add additional context in comments.

4 Comments

I applied it this way. console.log(isFound(product)) is return true or false properly but ngIf statement not working. *ngIf="isFound(product)" always return true.
console.log(isFound(product)) is return true or false properly but ngIf statement not working. *ngIf="isFound(product)" always return true.
i did it. I made typo, i fixed it and its works. thank you.
I have noticed funny behaviour when using a function as ngIf condition. Apparently Angular detects changes in the observed variables (in your case, it'd be product) when they are read in the function and the function (isFound) would be called repeatedly. If I where you, I'd check that isFound is not being called more than necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.