Home > Blockchain >  showing confirmation modal before changing the value of radio button in angular
showing confirmation modal before changing the value of radio button in angular

Time:05-11

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 >
      <h5 >Gender</h5>
      <div >
        <div >
          <input
            id="male"
            type="radio"
            
            (click)="clickGender($event)"
            value="male"
            name="gender"
            formControlName="gender"
          />
          <label >Male</label>
        </div>

        <div >
          <input
            id="female"
            type="radio"
            
            (click)="clickGender($event)"
            value="female"
            name="gender"
            formControlName="gender"
          />
          <label >Female</label>
        </div>
      </div>
    </div>

    <!-- Submit Button -->
    <button type="submit" >
      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

CodePudding user response:

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);
  }

https://stackblitz.com/edit/angular-material-confirm-dialog-using-matdialog-lfqfne?file=src/app/app.component.ts

  • Related