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(){}
...
}
To get your html value to evaluate as a boolean, use: [value]="true"
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With