49

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?

6 Answers 6

44

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!

Sign up to request clarification or add additional context in comments.

6 Comments

I think it's pertinent to point out that the name and the formControlName must be the same, as you have in your code - for both radios. A subtle point that some might miss.
2 other useful points - (1) you can still include a (change) event if you want to, although you will be subscribing to the changes anyway, so not sure if that would make sense. (2) as in your code you must not bind value as you do when using [(ngModel)] like [value]="" - so remember to remove the [] around value as @Chang shows here
name attribute is optional!
Not to clash with the other answers, but in my own testing, I have found that when setting a default value in the fb.group function, you do need the "[]" around value in your template.
How can we validate that one option is selected?
|
43

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.

2 Comments

I tried that but I guess I made a mistake before.. Thanks!
I tried using <input formControlName="option" type="radio" >.Value is not binding to radio button but for text box working.(<input formControlName="option" type="text" >)
6

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

  this.jobForm = this._fb.group({
                    id: [res["job"]["id"]],
                    job_status: [res["job"]["job_status"]**["id"].toString()**,Validators.required],
                    title: [res["job"]["title"],Validators.required]
                });

1 Comment

You can get round this by settings the value on the input using [] like this [value]="0" instead of value="0".
4

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.

<mat-radio-group formControlName="colorFilter" fxLayout="column" fxLayoutGap=".25rem">
    <mat-radio-button [value]="'Blue'">Blue things</mat-radio-button>
    <mat-radio-button [value]="'Red'">Red things</mat-radio-button>
    <mat-radio-button [value]="'Orange'">Orange things</mat-radio-button>
</mat-radio-group>

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

Comments

0
  <form [formGroup]="form" >
    <div class="row" style="margin-left: 20px; margin-bottom: 13px;">
      <label class="colmn radio" style="font-size: 17px;text-transform: capitalize;">
        <input type="radio" value="false" name="filter" formControlName="filter">
            Daily
        <span class="checkmark"></span>
      </label>

      <label class="colmn radio" style="font-size: 17px;text-transform: capitalize;margin-left: 56px">
        <input type="radio" value="true" name="filter" [checked]="true" formControlName="filter">     
            Monthly
        <span class="checkmark"></span>
      </label>

    </div>
  </form>



  form: FormGroup;

  constructor(    private _fb: FormBuilder,
   ) {

    this.form = _fb.group({
      filter: false
    });

    this.__filterChangeSubscription =  this.form.get('filter').valueChanges.subscribe(
      filterValue => {
        console.log(filterValue)
      }
    )
  }

Comments

-1

Angular Reactive form work for radio as same it works for input text box. Find the below HTML code and component use Email text box and radio button to select user.

Notable Point: formControlName must be used with a parent formGroup directive. So your formcontrol needs to bind inside formgroup

export class AppComponent  {

      form: FormGroup;
      someError = '';

      ngOnInit() {
        this.form = new FormGroup({
          'username': new FormControl(''),
          'password': new FormControl(''),
          'radiotest': new FormControl('')
        });
      }
      reset() {
        this.form.reset();
        this.someError = '';
      }
    }

Html Code:

<form [formGroup]="form">
    <label for="email">username</label>
    <input type="email" class="form-control" formControlName = "username">
    <input type="radio" formControlName="user" value="vimal"/>Vimal
    <input type="radio" formControlName="user" value="babu"/>Babu
</form>
<button (click)="reset()">Reset</button>
<h3> {{ someError }} </h3>
<h3> {{ form.value | json }} </h3>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.