Angular 2: ngModel binding for radio input of boolean type

In Angular 2, I’d like to bind 2 radio button input options in 1 group to a model property of boolean type, however either I’m not able to select one of the radio buttons or running into another incorrect binding issue.
I’ve tried the following in my html.

*.component.html:

Error: myModel.modelProperty is always: false, no matter which radio button is selected.

<div class="form-group">
        <label for="modelProperty">Model Property: </label>
        <form action="">
            <input type="radio" [ngModel]="_model.modelProperty"  (click)="_model.modelProperty=true" name="modelProperty" value=true>Yes<br>
            <input type="radio" [ngModel]="_model.modelProperty"  (click)="_model.modelProperty=false"  name="modelProperty" value=false>No
         </form>
</div> 

<div>{{_model.modelProperty}}</div>

*.component.html:

    Error: myModel.modelProperty is [Object object], only No radio button can be selected, if either Yes or No radio buttons is clicked.

<div class="form-group">
            <label for="modelProperty">Model Property: </label>
            <form action="">
                <input type="radio" [(ngModel)]="_model.modelProperty"   name="modelProperty" ngValue=true>Yes<br>
                <input type="radio" [(ngModel)]="_model.modelProperty"   name="modelProperty" ngValue=false>No
             </form>
    </div> 

    <div>{{_model.modelProperty}}</div>

I’m using the following

*.component.ts for all *.component.html options above:

import {Component, Input} from 'angular2/core';
import {NgForm}    from 'angular2/common';
import {Model}    from './model';
@Component({
  selector: 'my-form',
  templateUrl: 'app/.../*.component.html'
})

export class *Component {

      _model = new Model(..., false, ...); //false is the Model property: .modelProperty

      constructor(){}

      ...
}

3
Leave a Reply

avatar
3 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

To get your html value to evaluate as a boolean, use: [value]="true"

Jason
Guest

In similar cases I use your first version of code with [checked] instead of [ngModel].

This code works for me:

<form action="">
    <input type="radio" [checked]="_model.modelProperty" 
        (click)="setProperty($event.target.checked)"
        name="modelProperty">Yes<br>
    <input type="radio" [checked]="!_model.modelProperty" 
        (click)="setProperty(!$event.target.checked)" 
        name="modelProperty">No 
</form> 

setProperty(inChecked: boolean) { 
    this._model.modelProperty = inChecked; 
}

Jason
Guest

For boolean, [(ngModel)] is working with [value].
[(ngModel)] fails to checked by default with value.
For eg:

<input type="radio" 
   id="idYes" 
   name="Preferred-group" 
   [value]="true" 
   [(ngModel)]="IsContactPreffered"> 

works fine.