Radio button is not getting checked in angular 2

I have created two radio button for gender, I want to display radio button checked that was previously selected.

I have added below code in Template

<div class="form-group">
    <label>Gender</label>

    <div id="input-type">
        <label class="radio-inline">
            <input type="radio" formControlName="gender" [name]="'gender'" [value]="'male'"/> Male
        </label>
        <label class="radio-inline">
              <input type="radio" formControlName="gender" [name]="'gender'" [value]="'female'"/> Female
        </label>
    </div>
</div>

I have added below code in Component.

console.log(this.gender);  // I am getting 'male' here.
this.editProfile = new FormGroup({
     gender: new FormControl(this.gender || null)
});

Other value of the form is getting displayed but radio button is not getting checked.

Answers 1

  • I have found other solution. We can use below code

    <div class="form-group">
        <label>Gender</label>
          <div id="input-type">
              <label class="radio-inline">
                  <input type="radio" [checked]="editProfile.value.gender == 'male'" formControlName="gender" value="male"/> Male
              </label>
              <label class="radio-inline">
                    <input type="radio" [checked]="editProfile.value.gender == 'female'" formControlName="gender" value="female"/> Female
              </label>
          </div>
    </div>
    

Related Articles