I'm building a form in Angular2 with Reactive Forms. I'm using the FormBuilder to make a group of fields. For textboxes this works extremely well. But I can't find a formControl for radio buttons.
How does this work? Should I do <input formControlName="gender" type="radio">
just like I do with text input's?
One small to add about Reactive forms I noticed . If the value is an integer it needs to to changed to string or else it radio button wont be selected ..
Angular Material controls are (mostly) mature enough to use now.
Their samples mostly use ngModel, but here's how you can do it with formControlName.
I'm using angular/flex-layout to put my buttons in a vertical column.
(Could also have done
value='Blue'
for a constant or[value]="blueColorName"
to refer to a model property.I believe there may be an issue with
0
because it is not a 'truthy' value so watch out if you're binding to enums (may no longer be an issue).In your component, define your radio button as part of your form:
In your component HTML, construct your form:
I assume you know how to construct the entire form with your submit button, which isn't shown here.
When the form is submitted, you can get the value of the radio button here:
This will either be "female" or "male" depending on which radio button is checked.
Hope this helps you. Good luck!
Yes.
Form control directives use a
ControlValueAccessor
directive to communicate with the native element. There are different types ofControlValueAccessors
for each of the possible inputs. The correct one is chosen by theselector
of the value accessor directive. The selectors are based on whattype
the<input>
is. When you havetype="radio"
, then the value accessor for radios will be used.