Search code examples
angularradio-buttonangular-ngmodel

angular validate multiple choices in reactive form


I'm new to angular, I'm facing a problem with validation of the gender of the user by default the gender is not set, and the form is for update user data, maybe the user will set his gender and back again to update something else, now the user gender has been set so wanted to make it selected according to user data so here in my case data.general.gender is Male but nothing selected both are not selected

HTML

this.instructorGeneralForm = this._formBuilder.group({
  gender: ['', [Validators.required]]

Code

<div class="demo-inline-spacing">
   <div class="custom-control custom-radio">
      <input type="radio" 
      id="gender_male" 
      name="gender"
      formControlName="gender"
      class="custom-control-input" 
      [checked]="data.general.gender === 'Male'" [value]="'Male'"
      />
      <label class="custom-control-label" for="gender_male">I'm Male</label>
   </div>
   <div class="custom-control custom-radio">
      <input type="radio" 
      id="gender_female" 
      name="gender"
      formControlName="gender"
      class="custom-control-input" 
      value="Female"
      [checked]="data.general.gender === 'Female'" [value]="'Female'"
      />
      <label class="custom-control-label" for="gender_female">I'm Female</label>
   </div>
   <div *ngIf="submitted && generalForm.gender.errors" class="invalid-feedback"
   [ngClass]="{ 'd-block': submitted && generalForm.gender.errors }">
     <div *ngIf="generalForm.gender.errors.required">Gender is required</div>
   </div>
</div>

Solution

  • Setting the checked attribute conditionally would only reflect the checked state of radio box. This change in the state of radio won't reflect back in gender formControl.

    To fix the problem, you set patchValue of form

    this.instructorGeneralForm.patchValue({
      gender: data.general.gender,
    })
    

    And remove the [checked] attribute binding from the input radio box.

    Stackblitz