Search code examples
angularsweetalert2

Sweetalert2 unable to prevent a toast closing when clicked on the inside


I am using Sweetalert2 and I am unable to successfully prevent the closure of a Sweet-alert toast when the user clicks on the inside. I am using this toast feature for a notification that a certain task is occurring and I want it to remain open during the entirety of the process.

With that said, right now when you click on the inside of the toast, it gets dismissed. When you click on the outside of it, it remains open allowing the user to navigate through the app (so long as they don't refresh, of course.)

I'm not seeing anything in the documentation or GitHub Issues that would allow me to prevent a toast from closing when you click on the inside of the toast.

I created a StackBlitz here. https://stackblitz.com/edit/angular-ivy-8zcvm6?file=src%2Fapp%2Fapp.component.html

What would be some work-arounds or suggestions?

let toastr = Swal.fire({
  'imageUrl' : './assets/img/loading.svg',
  'imageWidth' : 100,
  'title' : 'Importing Files',
  'text' : 'Your import is running, keep working and we will let you know once it finishes.',
  'toast' : true,
  'position' : 'bottom-end',
  'showCancelButton' : false,
  'showConfirmButton' : false
});

Solution

  • Using a workaround, first you must store a reference to the toast, add a timer to it and immediately stop it (inside the didOpen function):

    persistentToast: any = null;
    
      openToast() {
        let toastr = Swal.fire({
          'title' : 'Importing Files',
          'text' : 'Your import is running, keep working and we will let you know once it finishes.',
          'toast' : true,
          'position' : 'bottom-end',
          'showCancelButton' : false,
          'showConfirmButton' : false,
          'timer': 500,
          'didOpen': () => {
            Swal.stopTimer();
          }
        });
        this.persistentToast = toastr;
      }
    

    Once you do this, the toast isn't dismissed when clicking on it. To close it, add a function you can call anytime: when your task finishes or assigning it to a button click:

    closeToast() {
        if (this.persistentToast)
          this.persistentToast.close();
      }