Ionic 5, ngModel not work as excepted on array model

Viewed 232

i'm using ionic 5 and angular, i tried to use ion-checkbox and the model target is an array:

user_id: any = [] // the model to target
user: any // data that filled from request api to be use on ngFor

on my html i use it like this:

<ion-checkbox [(ngModel)]="user_id" value="{{ user.id }}"></ion-checkbox>

but this make the all checkbox checked and unchecked at the same time.

2 Answers

check-box works differently. each control has it's name and value:

    this.form = this.formBuilder.group({
      demo: '',
      itemOne: '',
      itemTwo: '',
      itemThree: '',
    });
  <form [formGroup]="form">
    <ion-list>
      <ion-item>
        <ion-label floating>Placeholder Input</ion-label>
        <ion-input type="text" formControlName="demo"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label>Checkbox Item</ion-label>
        <ion-checkbox formControlName="itemOne" [checked]="checkMe"></ion-checkbox>
      </ion-item>
      <ion-item>
        <ion-label>Checkbox Item</ion-label>
        <ion-checkbox formControlName="itemTwo" checked="false"></ion-checkbox>
      </ion-item>
      <ion-item>
        <ion-label>Checkbox Item</ion-label>
        <ion-checkbox formControlName="itemThree" [checked]="false"></ion-checkbox>
      </ion-item>
    </ion-list>
  </form>

stackblitz

Here is an example to create dynamic list of checkboxes: https://forum.ionicframework.com/t/ion-checkbox-setting-values-and-using-as-an-array/87118/2

You can do something like this

<ion-checkbox [(ngModel)]="user_id" [checked]="user.id"></ion-checkbox>

Related