Angular2 is there a way to use a two way binding with a checkbox?

可紊 提交于 2019-12-12 12:49:13

问题


I want to use a two way binding for a checkbox, but if I use the [(ngModel)] it is showing true or false instead of the value of the checked item. Does anybody know how this is done?

If i want to use a two way binding and set it to "expression.value" in my case how do i do that:

<input type="checkbox" type="checkbox"/>&nbsp;Option 1</a></li>

I would like to bind the value of the checkbox in this case: Option 1 into the expression class.


回答1:


This is a known issue

  • https://github.com/angular/angular/issues/3406,
  • https://github.com/angular/angular/issues/6311

There are different workarounds like using event.target.checked instead of the value from the model.

You can use

<input type="checkbox"  
    (change)="expression && expression.Option1=$event.target.checked ? true : undefiend"
    [ngModel]="expression?.Option1">
<input type="checkbox"  
    (change)="expression && expression.Option2=$event.target.checked ? true : undefiend"
    [ngModel]="expression?.Option2">

Plunker example



来源:https://stackoverflow.com/questions/36544418/angular2-is-there-a-way-to-use-a-two-way-binding-with-a-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!