Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ngModel in ion-checkbox?

I'm trying to use with ngModel, but ngModel doesn't work there. My code:

<ion-checkbox *ngFor="#item of items" [(ngModel)]="item.checked">
  {{item.name}}
</ion-checkbox>

But I get an error:

EXCEPTION: Expression 'checked in AddInterestItem@5:2' has changed after it was checked. Previous value: 'false'. Current value: 'false' in [checked in AddInterestItem@5:2]

example data:

this.items = [ 
  {name: 'Dancing', checked: false}, 
  {name: 'Jazz', checked: false}, 
  {name: 'Metal', checked: true}, 
  {name: 'Pop', checked: false}, 
  {name: 'Rock\'n\'Roll', checked: false}, 
  {name: 'Folk Metal', checked: true} 
];
like image 564
Maksim Avatar asked Jan 21 '16 07:01

Maksim


2 Answers

I am not familiar with <ion-checkbox>. But when i tried to repeat your story with normal <input type="checkbox" />, I couldn't get success by applying ngFor to input type="checkbox" directly. So what I did, I took <ul><li *ngFor="#item of items" > and put my input type="checkbox" within it and it started working as expected.

I feel like MyAnswer could help you further.

doesn't work in mycase

<input  type="checkbox" *ngFor="#item of items" [(ngModel)]="item.checked" />{{item.name}}  
/* I don't know some error occurs. you can check my plunkr by modifying it/*.

Worked properly

    <ul>
        <li *ngFor="#item of items">{{item.name}}
            <input type="checkbox" [(ngModel)]="item.checked" />
        </li>
    </ul>
like image 188
Nikhil Shah Avatar answered Oct 06 '22 00:10

Nikhil Shah


Just a quick update for Ionic 4:

HTML:

<ion-checkbox [(ngModel)]="iLikeIt.isChecked"></ion-checkbox>

Ts:

iLikeIt={isChecked:false}
like image 21
diacode Avatar answered Oct 06 '22 00:10

diacode