Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Reactive Forms formControl for radio buttons

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?

like image 500
Mike Bovenlander Avatar asked Oct 10 '16 10:10

Mike Bovenlander


People also ask

Can we give Formcontrolname to button?

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

What is difference between FormBuilder and FormControl?

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.


2 Answers

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.

like image 141
Paul Samsotha Avatar answered Sep 21 '22 01:09

Paul Samsotha


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!

like image 22
Chang Avatar answered Sep 17 '22 01:09

Chang