42

I have a simple boolean property valid in my object document and need to bind it to radio-inputs.

This is what I have so far:

<input type="radio" name="valid" id="validTrue" (click)="document.valid = true" [checked]="document.valid"/>
<input type="radio" name="valid" id="validFalse" (click)="document.valid = false" [checked]="!document.valid"/>

At least setting the property on click works but its state is not displayed by the radio-inputs. Looking in the developer console of my browser I found out that a property ng-reflect-checked is set but it doesn't seem to have impact on the HTML radio-input.

What am I doing wrong?
Does anyone have a working "angular2-boolean-radio-input" snippet?

3
  • which angular 2 version you are using Commented Jun 29, 2016 at 10:53
  • New RC.3 forms or deprecated forms? Commented Jun 29, 2016 at 10:53
  • Sorry... i am on rc3 using the new forms. Commented Jun 29, 2016 at 11:03

1 Answer 1

124

In the new forms module this might do what you want

  <input type="radio" name="food" [(ngModel)]="document.valid" [value]="true">
  <input type="radio" name="food" [(ngModel)]="document.valid" [value]="false">

see also design doc for the new forms module

Sign up to request clarification or add additional context in comments.

11 Comments

Your're right. It is that simple. I think i already tried this but forget to put the vale attribute in square brackets.
Without the [] you get true and false as string which I guess are both the value true in JS/TS (not sure, I don't use it much)
I've tried to do this but my radio buttons become unchecked. I need the one setted up with true value to load as checked by default, while the other one stay unchecked. How could I activate this behavior?
With [value]="false" you bind the boolean literal false to the value property of the element and the @Input() value:boolean; of the directive/component. If such a property or input doesn't exist an exception is thrown. With value="false" you bind the string "false" to the value attribute. If the HTML element supports such an attribute it might convert it to boolean and assign the value to its property. If a directive/component is hosted on that element the string will be assigned to it value input. The inputs gets a string value passed.
@DarionN If you use value then normal attribute binding is used, which passes values always as string. With [value] it becomes a property binding that passes all values as original types. With [] the part in "..." is interpreted as code and true is passed as boolean value, while with value="true" "true" is passed as string. In JS "false" is also truthy, so with a string value this can not work.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.