1

I am using Angular 12 with PrimeNG in my application to implement a custom confirm() function. The use case is the following:

When the user clicks on any checkbox or radio button on the form, before the event triggering, a confirmation message should be shown, which asks whether the user actually wants to proceed or not.

In order to implement this, I use event.preventDefault(); in the first place to prevent the selection, then if the user clicks "Yes" on the custom confirm message, I want to re-trigger the just prevented event. Code example below:

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

}

Am I on the "right path" for this use case? I know I could specifically for each case set the value checked if it is a checkbox, for example:

this.event.currentTarget.checked = true;

or accordingly if it is a radio button, but I want to implement this in a "generic way", any ideas?

Thanks in advance!

NickAth
  • 1,089
  • 1
  • 14
  • 35

1 Answers1

1

SOLVED

Following this, what I did was passing the target element that invoked the click event inside the openConfirmDialog() function, then on the accept event of the confirmationService, I re-click() manually the input element. For this functionality, we I needed to introduce a boolean flag ( let fromManualClick = false )

Code Solution

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: () => {

  }
 });
}
NickAth
  • 1,089
  • 1
  • 14
  • 35