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 ?
I was looking for the right method to handle those radio buttons here is an example for a solution I found here:
Notice the onSelectionChange that passes the current element to the method.
Radio input doesn't seem to be supported yet. There should be a radio input value accessor (similar to checkbox's one, where it sets 'checked' attr here) but I didn't find any. So I implemented one; you can check it out here.
This may be not the correct solution but this one is also option hope it will help someone.
Till now i had getting the value of radioButtons using (click) method like following:
and in the .ts file i have set the value of predefined variable to getter value of
onChange
function.But after searching i found good method i have't tried yet but it seems this one is good using
[(ng-model)]
link is here to github here. this is usingRadioControlValueAccessor
for the radio as well as checkbox too. here is the working #plnkr# for this method here .My manual workaround, which involves manually updating
model.options
when a new radio button is selected:This Plunker demonstrates the above, as well as how to use a button to change the selected radio button -- i.e., to prove that the data binding is two-way:
[value]="item" using *ngFor also works with Reactive Forms in Angular 2 and 4
use [value]="1" instead of value="1"
Edit:
As suggested by thllbrg "For angular 2.1+ use
[(ngModel)]
instead of[(ng-model)]
"