45
votes

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

6 Answers

40
votes

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.

39
votes

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!

6
votes

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]
                });
3
votes

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

0
votes
  <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)
      }
    )
  }
-1
votes

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>