加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

typescript – Angular 2:用于布尔类型的无线电输入的ngModel绑

发布时间:2020-12-17 09:15:53 所属栏目:安全 来源:网络整理
导读:在Angular 2中,我想将1组中的2个单选按钮输入选项绑定到布尔类型的模型属性,但是我要么无法选择其中一个单选按钮,要么遇到另一个错误的绑定问题. 我在我的 HTML中尝试过以下内容. * .component.html: Error: myModel.modelProperty is always: false,no mat
在Angular 2中,我想将1组中的2个单选按钮输入选项绑定到布尔类型的模型属性,但是我要么无法选择其中一个单选按钮,要么遇到另一个错误的绑定问题.
我在我的 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]的第一个代码版本.

这段代码适合我:

<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; 
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读