Angular - 在事件 event.preventDefault() 后重新触发事件

Angular - Re-trigger event after event has been event.preventDefault()

我在我的应用程序中使用 Angular 12PrimeNG 来实现 custom confirm() 功能。用例如下:

当用户单击表单上的任何复选框或单选按钮时,在事件触发之前,应显示一条确认消息,询问用户是否真的要继续.

为了实现这一点,我首先使用 event.preventDefault(); 来防止选择,然后如果用户在自定义确认消息上单击“是”,我想 重新-触发 刚刚阻止的事件。下面的代码示例:

onCheckboxChange

onCheckboxChange(event: Event) {
   event.preventDefault(); // prevent the default click in the first place

   this.openConfirmDialog( () => {
     // re-trigger event here, for example 'event.trigger();'
  }, event);
}

openConfirmDialog

openConfirmDialog(acceptAsync: any, event: Event) {
    this.confirmationService.confirm({
    message: 'Are you sure you want to make this change? Progress will be lost',
    accept: () => {
    //Actual logic to perform a confirmation
    acceptAsync();
   },
   reject: () => {
    event.preventDefault();
   }
});

}

对于这个用例,我走的是“正确的道路”吗?我知道我可以专门为每种情况设置选中的值,如果它是一个复选框,例如:

this.event.currentTarget.checked = true;

或者相应地,如果它是一个单选按钮,但我想以“通用方式”实现它,有什么想法吗?

提前致谢!

已解决

this 之后,我所做的是在 openConfirmDialog() 函数中传递调用点击事件的目标元素,然后在 confirmationService 的 accept 事件中,我重新 - click() 手动输入元素。对于此功能,我们需要引入 boolean flag ( let fromManualClick = false )

代码解决方案

onCheckBoxChange

onCheckboxChange(event: Event) {
  if(fromManualClick){
    event.preventDefault(); // prevent the default click in the first place

    this.openConfirmDialog( () => {
    // my logic here
    }, (event.currentTarget as HTMLInputElement));
  }
  fromManualClick = false;
}

openConfirmDialog

openConfirmDialog(acceptAsync: any, srcElement: HTMLInputElement) {
  this.confirmationService.confirm({
  message: 'Are you sure you want to make this change?',
  accept: () => {
    acceptAsync();
    //re-trigger the click element
    fromManualClick = true;
    srcElement.click();
  },
  reject: () => {

  }
 });
}