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?
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
})
The correct answer helped me too, although I had to solve how to catch the "Uncaught in promise" error. I thought I'd just add it here for completion if anyone found it helpful using the cancelButton.
swal({
//code
}).then(()=> {
//code
},(error: any) => console.log(error));