Search code examples
javascripthtmlangularionic-frameworkangular-ng-if

Why does my ionic button not start in the correct state when using ngIf with a boolean property bound to an ionic-checkbox?


I am currently trying to set up a list of ingredients with a checkbox and a conditional button, but having issues with the default state. I want it so that the button is only visible when the checkbox is unchecked so that the ingredient can be added to a grocery list.

The issue is that when it loads the page, if an ingredient is unchecked, the button is not shown. It only appears after checking the checkbox and then unchecking it (and then anytime it is unchecked after that). The problem is just in the default state.

It also seems to turn the entire item in to a clickable object when using the *ngIf statement where it doesn't seem to have the same behavior without (can only click on the actual checkbox in order to check it).

HTML:

<div *ngIf="product.ingredients">
   <h5>Ingredients: </h5>
   <ion-list *ngFor="let ingredient of product.ingredients; let i = index;" lines="none" 
   class="child-list">
      <ion-item>
         {{ ingredient.name }}
         <ion-checkbox slot="start" [(ngModel)]="ingredient.isOwned"></ion-checkbox>
         <ion-button (click)="addIngredient(ingredient)" slot="end" shape="round" *ngIf="!ingredient.isOwned">
            <ion-icon name="bag-add-outline"></ion-icon>
         </ion-button>
      </ion-item>
   </ion-list>
</div>

Then in the component's TS file, I am receiving a product object that we expect to look like this:

JSON:

{
   "ingredients": [
   {
      "name": "greek yogurt",
      "isOwned": "false"
   },
   {
      "name": "turmeric",
      "isOwned": "true"
   },
   {
      "name": "heavy cream",
      "isOwned": "false"
   }
   ]
}

This is how I would expect this portion to look with the given json example:

Example List Formatting

EDIT: It was the JSON input causing the issues. Thanks for the answers!


Solution

  • Please replace your JSON with this

    {
       "ingredients": [
       {
          "name": "greek yogurt",
          "isOwned": false
       },
       {
          "name": "turmeric",
          "isOwned": true
       },
       {
          "name": "heavy cream",
          "isOwned": false
       }
       ]
    }
    

    You need to pass boolean value in isOwned, because 'false' would mean true