简体   繁体   中英

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(){}

      ...
}

要使您的html值作为布尔值计算,请使用: [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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM