简体   繁体   English

如何在 ion-checkbox 中使用 ngModel?

[英]How to use ngModel in ion-checkbox?

I'm trying to use with ngModel, but ngModel doesn't work there.我正在尝试与 ngModel 一起使用,但 ngModel 在那里不起作用。 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.例外:表达式“在 AddInterestItem@5:2 中检查”在检查后已更改。 Previous value: 'false'.以前的值:'假'。 Current value: 'false' in [checked in AddInterestItem@5:2]当前值:[在 AddInterestItem@5:2 中检查] 中的“false”

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} 
];

I am not familiar with <ion-checkbox> .我不熟悉<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.但是当我试图用普通的<input type="checkbox" />重复你的故事时,我无法通过将 ngFor 直接应用于input type="checkbox"来获得成功。 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.所以我做了什么,我把<ul><li *ngFor="#item of items" >放在里面,然后我的input type="checkbox"开始按预期工作。

I feel like MyAnswer could help you further.我觉得MyAnswer可以进一步帮助您。

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>

Just a quick update for Ionic 4:只是 Ionic 4 的快速更新:

HTML: HTML:

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

Ts: :

iLikeIt={isChecked:false}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM