I'm building a form in Angular 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 use <input formControlName="gender" type="radio">
just like I use with text input's?
Since you can't bind formcontrolname to a 'none user input' html element. Reactive forms is used to handler user inputs, and button is not the case..
In Angular, a reactive form is a FormGroup that is made up of FormControls. The FormBuilder is the class that is used to create both FormGroups and FormControls.
Should I do
<input formControlName="gender" type="radio">
just like I do with text input's?
Yes.
How does this work?
Form control directives use a ControlValueAccessor
directive to communicate with the native element. There are different types of ControlValueAccessors
for each of the possible inputs. The correct one is chosen by the selector
of the value accessor directive. The selectors are based on what type
the <input>
is. When you have type="radio"
, then the value accessor for radios will be used.
In your component, define your radio button as part of your form:
export class MyComponent { form: FormGroup; constructor(fb: FormBuilder){ this.form = fb.group({ gender: "" }); } }
In your component HTML, construct your form:
<div class="form-group"> <label>Please select your gender</label> <div class="row"> <label class="md-check"> <input type="radio" value="female" name="gender" formControlName="gender"> Female </label> <label class="md-check"> <input type="radio" value="male" name="gender" formControlName="gender"> Male </label> </div> </div>
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:
let genderValue = this.form.value.gender;
This will either be "female" or "male" depending on which radio button is checked.
Hope this helps you. Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With