Angular2 ReactiveFormsControl: how to bind radio buttons?

smartmouse picture smartmouse · Oct 20, 2016 · Viewed 7.5k times · Source

I'm using ReactiveFormsModule of Angular2 to create a component that contains a form. Here is my code:

foo.component.ts

constructor(fb: FormBuilder) {
    this.myForm = fb.group({
        'name': ['', Validators.required],
        'surname': ['', Validators.required],
        'gender': []
    });
}

foo.component.html

<div class="two fields">
    <div class="four wide field">
        <label>Name*</label>
        <input type="text" [formControl]="myForm.controls.name"/>
    </div>

    <div class="four wide field">
        <label>Surname*</label>
        <input type="text" [formControl]="myForm.controls.surname"/>
    </div>
</div>

<div class="inline fields">
    <label for="gender">Gender</label>
    <div class="field">
        <div class="ui radio checkbox">
            <input type="radio" name="gender" checked="" tabindex="0" class="hidden" [formControl]="myForm.controls.gender">
            <label>Male</label>
        </div>
    </div>
    <div class="field">
        <div class="ui radio checkbox">
            <input type="radio" name="gender" tabindex="0" class="hidden" [formControl]="myForm.controls.gender">
            <label>Female</label>
        </div>
    </div>
</div>

The code i posted above doesn't work: if i click on one of the two radio buttons it always select the second one and i can't change it.

What is the right way to use FormControl with radio (or checkbox)?

Answer

Fırat K&#220;&#199;&#220;K picture Fırat KÜÇÜK · Apr 4, 2017

For other than string values you may use [value] attribute and also [checked] attribute should be used for initial values.

export enum Gender {
  FEMALE = 1,
  MALE   = 2
}

export class SampleGenderComponent implements OnInit {

  public form: FormGroup;
  public Gender = Gender;

  constructor(fb: FormBuilder) {

    this.form = fb.group({
      gender    : [
        Gender.FEMALE,
        []
      ]
    });
  }
}
<div class="inline fields">
  <label for="gender">Gender</label>
  <div class="field">
    <div class="ui radio checkbox">
      <input type="radio" name="gender" [value]="Gender.MALE" [checked]="form.controls['gender'].value === Gender.MALE">
      <label>Male</label>
    </div>
  </div>
  <div class="field">
    <div class="ui radio checkbox">
      <input type="radio" name="gender" [value]="Gender.FEMALE" [checked]="form.controls['gender'].value === Gender.FEMALE">
      <label>Female</label>
    </div>
  </div>
</div>