Angular2 - Sweetalert custom button click doesn´t work

Viewed 1723

I create a custom button inside a footer in Sweetalert2 like this.

    Swal.fire({
          icon: "question",
          showCancelButton: true,
          confirmButtonColor: "#1976d2",
          cancelButtonText: "No",
          confirmButtonText: "Sí",
          footer: "<button (click)='withoutread()' class='btn btn-info'>Test</button>"
  })

  withoutread() {
    console.log('hello');
  }

The problem: The function withoutread doesn´t call properly, console.log('hello') doesn´t show hello in console.

So: What´s wrong in this code?

4 Answers

Working !

Swal.fire({
  icon: 'error',
  title: 'Oops...',
  text: 'Something went wrong!',
  footer: '<button id="buttonId">Test</button>'
})

document.getElementById('buttonId').onclick = function(){
    alert('do Something');
}

Your click method in the way you have implemented it would not be accessible since the method withoutread() exists outside of the scope of the SweetAlert instance.

Aside from the SweetAlert configurations available for capturing user input, you could include a third, custom button and capture the click using event delegation as described here

Try this

footer: "<a><button (click)='withoutread()' class='btn btn-info'>Test</button></a>"

OR

footer: "<a onclick='withoutread()'><button class='btn btn-info'>Test</button></a>"

You have to user onclick rather than (click). Please look at the below working code.

Swal.fire({
      icon: "question",
      showCancelButton: true,
      confirmButtonColor: "#1976d2",
      cancelButtonText: "No",
      confirmButtonText: "Sí",
      footer: "<button onclick='withoutread()' class='btn btn-info'>Test</button>"
})
 function withoutread() {
     alert('dd') 
 }

You can also review the JSFiddle link here

Related