3

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.

Sireini
  • 4,142
  • 12
  • 52
  • 91

1 Answers1

3

This is a known issue

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • As you can see it is logging the event itself: http://i66.tinypic.com/2qd4z6t.png – Sireini Apr 11 '16 at 09:46
  • I updated the answer. I mentioned it in the text but forgot to update the code. – Günter Zöchbauer Apr 11 '16 at 09:48
  • It is logging value: "on" and not Option1 in my case – Sireini Apr 11 '16 at 09:51
  • Sorry, It should be `$event.target.checked` – Günter Zöchbauer Apr 11 '16 at 10:00
  • Wait i think you do not understand what my goal is. I have got multiple checkboxes Option1, option2 etc I want to bind the checked Option into my expression class. So that if i log the value of the checked items I see the label of the checked Option1, Option2 – Sireini Apr 11 '16 at 10:04
  • Then change `expression.value` to `expression.Option1` and `expression?.value` to `expression?.Option1`. – Günter Zöchbauer Apr 11 '16 at 10:06
  • input type="checkbox" (change)="expression ? expression.value=$event.target.checked : null" [ngModel]="expression?.value">Option 1 This is one of many options i want to bind **Option1** if it is checked to the class. – Sireini Apr 11 '16 at 10:09
  • Not sure what do to with your last comment. You need to change `.value` to the name of the property you want to bind to. – Günter Zöchbauer Apr 11 '16 at 10:11
  • Yes i understand that. I do not want to bind the checkbox true or false, I want to bind the value of the checked item. So if Option 3 and 4 are checked I want to see Option 3 and 4 in my log. – Sireini Apr 11 '16 at 10:14
  • console log of the expression object as you can see in my first comment – Sireini Apr 11 '16 at 10:16
  • How do i do this when the options are set with ngFor – Sireini Apr 11 '16 at 12:11
  • Please add some code to your question that demonstrates what you actually try to accomplish. In this case I'd suggest to create a new question. – Günter Zöchbauer Apr 11 '16 at 12:18