Issue
The radio button inside reactiveform needs to show a confirmation modal in certain situations before changing the value. If the confirm button clicked then change the value. If the cancel button clicked then the radio value remain the same. So inside the click event handler, I'm using the preventDefault to prevent the radio button change immediately.
app.component.html
<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
<!-- Gender -->
<div class="group-gap">
<h5 class="mb-3">Gender</h5>
<div class="d-block my-3">
<div class="custom-control custom-radio">
<input
id="male"
type="radio"
class="custom-control-input"
(click)="clickGender($event)"
value="male"
name="gender"
formControlName="gender"
/>
<label class="custom-control-label">Male</label>
</div>
<div class="custom-control custom-radio">
<input
id="female"
type="radio"
class="custom-control-input"
(click)="clickGender($event)"
value="female"
name="gender"
formControlName="gender"
/>
<label class="custom-control-label">Female</label>
</div>
</div>
</div>
<!-- Submit Button -->
<button type="submit" class="btn btn-danger btn-lg btn-block">
Submit
</button>
</form>
app.component.ts
async clickGender(e) {
e.preventDefault();
const value = e.target.value;
const otherFieldTrue = this.registrationForm.get('otherField').value;
if (otherFieldTrue && value !== 'male') {
let confirm = await this.showConfirm();
if (!confirm) {
return;
}
}
this.registrationForm.get('gender').setValue(value);
}
The problem is after changing the value by clicking the confirm button the value of the radio can't be switched back. Also, when there is no need to show the modal, the radio can't be changed.
Here is the stackblitz example: enter link description here
Solution
Its because you are always e.preventDefault()
which disables native browser control value switch. Moving it inside if
statement fixes the issue
async clickGender(e) {
const value = e.target.value;
const otherFieldTrue = this.registrationForm.get('otherField').value;
if (otherFieldTrue && value !== 'male') {
e.preventDefault(); //Prevent radio switch only here
let confirm = await this.showConfirm();
if (!confirm) {
return;
}
}
this.registrationForm.get('gender').setValue(value);
}
Answered By - Antoniossss
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.