Sweet Alert in Ionic apps

Hello dev, today we are going to learn how to integrate Sweet Alert in Ionic Apps. In web development, providing notifications to users is crucial for enhancing the user experience and keeping them informed about important updates or actions.

Step 1: Install Sweet Alert in our Ionic Project

The process is quite simple, just run install from the console using a package manager, in this case npm.

npm install sweetalert2

Step 2: Importation

We need call the Sweet Alert library on the pages where we want to use it. To do this, we just need to import it as usual.

import Swal from 'sweetalert2'

Step 3: Display the alerts

In the official documentation, we can find all the examples of implementation. Let’s try one to analyze what happens:

Swal.fire({
  title: 'Error!',
  text: 'Do you want to continue',
  icon: 'error',
  confirmButtonText: 'Cool'
});
sweet alert error
sweet alert error

It’s a complete disaster, isn’t it? The good thing is that it’s easily fixed, we just need to add this line of code every time we invoke the library.

heightAuto: false

Our code would look like this:

sweet alert implementation fixed
sweet alert implementation fixed

The result would be like this:

sweet alert working correctly
sweet alert working correctly

Let’s modify the code a bit. You can find all the information regarding it in its official documentation.

sweet alert, modified code
sweet alert, modified code

And we will have this:

sweet alert, modified code-2
sweet alert, modified code-2

How do I implement it?

Generally, we need to display alerts in different parts or stages of our application, in this case, or pages. So, it becomes tedious to implement the same thing as many times as necessary. To avoid that, I create a new service and inside it, I create some generic functions to which I can pass parameters. Something like this:

sample implementation
sample implementation

We just have to invoke the service on the page we want, call the function, and pass it parameters, in this case, title, text, and icon.

calling the function present_alert
calling the function present_alert
html file calling sample_alert function
html file calling sample_alert function
sweet alert dj’s implementation
sweet alert dj’s implementation

And that’s all, friends. The sky is the limit. Consult the official documentation to learn more, for example, execute functions when buttons are pressed or when an alert automatically closes after a few seconds.

Leave a Reply

Your email address will not be published. Required fields are marked *