Search code examples
angularsweetalertsweetalert2

How to call method i sweetalert 2


In my angular 4 project I am using a theme with sweetalert 2, I want to call my method when user click on the confirm button, but it seems that I can't call any method inside then function

swal({
  title: 'Are you sure?',
  text: "You won't be able to revert this!",
  type: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, delete it!'
}).then(function () {

  // I want to call my method here but I can't do this.myMethod()

})

I know It's not the angular sweetalert but is it possible to make it work without change?


Solution

  • Use the arrow function notation () =>. When you use the function keyword, you loose the access to this. Change your code to the below instead:

    swal({
      title: 'Are you sure?',
      text: "You won't be able to revert this!",
      type: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, delete it!'
    }).then(()=> {
    
      this.myMethod(); // this should execute now
    
    })