在Angular 2中,我想将1组中的2个单选按钮输入选项绑定到布尔类型的模型属性,但是我要么无法选择其中一个单选按钮,要么遇到另一个错误的绑定问题.
我在我的 HTML中尝试过以下内容.
我在我的 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>
我正在使用以下内容
* .component.ts适用于以上所有* .component.html选项:
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(){} ... }
在类似的情况下,我使用[checked]代替[ngModel]的第一个代码版本.
原文链接:https://www.f2er.com/angularjs/140798.html这段代码适合我:
<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; }