Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
722 views
in Technique[技术] by (71.8m points)

angular - How to bind to radio buttons in angular2 beta 6

How does one achieve radio button binding in beta 6?

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).

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update

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

Original

Several issues.

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.?

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...