如何绑定到 angular2 beta 6 中的单选按钮 [英] How to bind to radio buttons in angular2 beta 6

查看:20
本文介绍了如何绑定到 angular2 beta 6 中的单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 beta 6 中如何实现单选按钮绑定?

How does one achieve radio button binding in beta 6?

我为 beta 0 找到了一个很棒的 plnkr(参见 http://plnkr.co/edit/aggee6An1iHfwsqGoE3q?p=preview),但是当我尝试将其更新到 beta 6 时,它严重崩溃(请参阅 http://plnkr.co/edit/voU933?p=preview).

I found a great plnkr for beta 0 (see http://plnkr.co/edit/aggee6An1iHfwsqGoE3q?p=preview), but when I try to update it to beta 6 it breaks horribly (see http://plnkr.co/edit/voU933?p=preview).

我查看了为单选选项添加内置支持的提交(参见 https://github.com/angular/angular/commit/e725542),给出了这个例子

I took a look at the commit that added built-in support for radio options (see https://github.com/angular/angular/commit/e725542), which gives this example

@Component({
  template: `
    <input type="radio" name="food" [(ngModel)]="foodChicken">
    <input type="radio" name="food" [(ngModel)]="foodFish">
  `
})
class FoodCmp {
  foodChicken = new RadioButtonState(true, "chicken");
  foodFish = new RadioButtonState(false, "fish");
}

但到目前为止,我尝试完成这项工作的结果很像我失败的 plnkr.

but my attempts to make that work have so far ended up quite like my failed plnkr.

推荐答案

更新

Radio 在 RC.4 和新的表单模块中运行良好.例如,参见 https://stackoverflow.com/a/38590919/217408

Radio is working fine in RC.4 and the new forms module. See for example the Plunker in https://stackoverflow.com/a/38590919/217408

原创

几个问题.

使用 <script src="https://code.angularjs.org/2.0.0-beta.7/angular2.min.js"></script> 导致例外.我通过删除 `min.?

Using <script src="https://code.angularjs.org/2.0.0-beta.7/angular2.min.js"></script> caused an exception. I got rid of it by removing `min.?

无线电绑定值 {checked: true} 而不是 value.这显然是一个错误,可能与这些相同

The radio binds the value {checked: true} instead of value. This is obviously a bug and probably the same as these

  • Radio button data binding and form validation not working
  • Cannot select multiple radio buttons in same control group (fixed)
  • input type=radio not handled correctly by ng-model (fixed)
  • https://github.com/angular/angular/issues/7642

我用一个丑陋的解决方法让它工作.请参阅 https://plnkr.co/edit/988PSJKXCfrUXfLOGgyg?p=preview>

I got it working with an ugly workaround. See https://plnkr.co/edit/988PSJKXCfrUXfLOGgyg?p=preview

    <input type="radio" [ngModel]="{checked: model.sex == 'male'}" (ngModelChange)="model.sex='male'"  name="sex" value="male">Male<br>
    <input type="radio" [ngModel]="{checked: model.sex == 'female'}"  (ngModelChange)="model.sex='female'" name="sex" value="female">Female

这篇关于如何绑定到 angular2 beta 6 中的单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆