在 angular 中更改单选按钮的值之前显示确认模式

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

reactform 中的单选按钮在某些情况下需要在更改值之前显示确认模式。如果单击确认按钮,则更改值。如果单击取消按钮,则单选值保持不变。所以在点击事件处理程序中,我使用 preventDefault 来防止单选按钮立即更改。

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

问题是单击确认按钮更改值后,收音机的值无法切换回来。还有,不需要显示模态时,单选不能改

这是 stackblitz 示例: enter link description here

这是因为您总是 e.preventDefault() 禁用本机浏览器控件值开关。将其移入 if 语句可解决问题

  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%2Fapp%2Fapp.component.ts