Angular 2: ng Boolean radio input binding model

In Angular 2, I would like to associate 2 input options for the switch in 1 group with the model property in the boolean type, however either I cannot select one of the switches or work in the other wrong mandatory problem. I 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 use 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(){} ... } 
+5
source share
3 answers

To make your html value evaluate to boolean, use: [value]="true"

+4
source

In such cases, I use your first version of the 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; } 
+3
source

For boolean, [(ngModel)] works with [value] . [(ngModel)] is not checked by default with value . For example: - <input type="radio" id="idYes" name="Preferred-group" [value]="true" [(ngModel)]="IsContactPreffered"> works fine.

+2
source

Source: https://habr.com/ru/post/1247753/


All Articles