I want to use radio button in a form using Angular 2
Options : <br/>
1 : <input name="options" ng-control="options" type="radio" value="1" [(ng-model)]="model.options" ><br/>
2 : <input name="options" ng-control="options" type="radio" value="2" [(ng-model)]="model.options" ><br/>
model.options initial value is 1
when the page is loaded the first radio button isn't checked and the modifications aren't binded to the model
Any Idea ?
Here is a solution that works for me. It involves radio button binding--but not binding to business data, but instead, binding to the state of the radio button. It is probably NOT the best solution for new projects, but is appropriate for my project. My project has a ton of existing code written in a different technology which I am porting to Angular. The old code follows a pattern in which the code is very interested in examining each radio button to see if it is the selected one. The solution is a variation of the click handler solutions, some of which have already been mentioned on Stack Overflow. The value added of this solution may be:
This solution involves
Example:
...
...
When the user clicks a radio button, the selectButton method of the helper class gets invoked. It is passed the model for the radio button that got clicked. The helper class sets the boolean "selected" field of the passed in model to true, and sets the "selected" field of all the other radio button models to false.
During initialization the component must construct an instance of the helper class with a list of all radio button models in the group. In the example, "radioButtonGroupList" would be an instance of the helper class whose code is:
Note - radio button binding is now a supported feature in RC4 onwards - see this answer
Radio button example using custom RadioControlValueAccessor similar to CheckboxControlValueAccessor (Updated with Angular 2 rc-1)
App.ts
template.html
radio_value_accessor.ts
Source : https://github.com/angular2-school/angular2-radio-button
Plunker live demo : http://plnkr.co/edit/aggee6An1iHfwsqGoE3q?p=preview
This Issue is solved in version Angular 2.0.0-rc.4, respectively in forms.
Include
"@angular/forms": "0.2.0"
in package.json.Then extend your bootstrap in main. Relevant part:
I have this in .html and works perfectly: value: {{buildTool}}
I've created a version by using just a click event on the elements loaded and passing the value of the selection into the function "getSelection" and updating the model.
In your template:
Your class:
See example: https://plnkr.co/edit/2Muje8yvWZVL9OXqG0pW?p=info
Simplest solution and workaround:
Here is the best way to use radio buttons in Angular2. There is no need to use the (click) event or a RadioControlValueAccessor to change the binded property value, setting [checked] property does the trick.
I published an example of using radio buttons: Angular 2: how to create radio buttons from enum and add two-way binding? It works from at least Angular 2 RC5.