Search code examples
angularionic-frameworkionic4indexofangular-ng-if

Angular ngIf with array.indexOf only work once


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.


Solution

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