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 >
<div >
<input type="radio"
id="gender_male"
name="gender"
formControlName="gender"
[checked]="data.general.gender === 'Male'" [value]="'Male'"
/>
<label for="gender_male">I'm Male</label>
</div>
<div >
<input type="radio"
id="gender_female"
name="gender"
formControlName="gender"
value="Female"
[checked]="data.general.gender === 'Female'" [value]="'Female'"
/>
<label for="gender_female">I'm Female</label>
</div>
<div *ngIf="submitted && generalForm.gender.errors"
[ngClass]="{ 'd-block': submitted && generalForm.gender.errors }">
<div *ngIf="generalForm.gender.errors.required">Gender is required</div>
</div>
</div>
CodePudding user response:
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.