Angular 16 Popup Notification with SweetAlert2 Example

Last Updated on by in Angular
This tutorial explains to you how to show an alert or popup notification in Angular 16 with SweetAlert2 npm package. We will learn how to use sweetalert2 in angular altogether, and learn how to display the alert boxes with user-centric information.We will follow all the process gradually and steadily to install SweetAlert2 in angular. I will try to break down the entire tutorial in small steps to demonstrate angular SweetAlert2 example.

If you want to provide important information to your user from UX point of you or want to grab their attention. Then this SweetAlert2 angular example tutorial is going to be helpful for you.

The SweetAlert2 is a powerful library, and it offers a beautiful, responsive, customizable, accessible (WAI-ARIA) replacement for JavaScript’s popup boxes with absolutely zero dependencies needed.

Angular 16 SweetAlert Popup Notification Tutorial

  • Prerequisite
  • Install Angular Application
  • Install SweetAlert2 in Angular
  • Register SweetAlert in Component
  • Display Notification
  • Run Development Server

Prerequisite

  • Node
  • npm
  • SweetAlert2 Pacakage
  • Angular CLI
  • Latest Angular
  • Code Editor or IDE

Order of precedence starts with installing Node.js and NPM on your local development machine. If you do not have the mentioned tools installed, then check this article to comprehend the installation process for Node and NPM:

Download and Install Node and npm on macOS, Windows & Linux. .

Install Angular Application

Run the following command to install the latest version of Angular CLI.

npm install -g @angular/cli@latest

Preferably, this step consist of installing a fresh angular application on your development machine.

Run the following command, answer some questions asked by angular CLI.

ng new angular-sweetalert-demo

Eventually, the installation is completed. Get inside the project folder.

cd ng new angular-sweetalert-demo

Install SweetAlert2 in Angular 12

Install sweetalert2 npm package for displaying beautiful notifications and alert in angular 12. Run the command in your terminal:

npm i sweetalert2

In order to show attractive notifications to users, you have to first incorporate the sweetalert2 CSS path in angular.json file.

....
....
....
"styles": [

      "src/styles.css",
      "node_modules/sweetalert2/src/sweetalert2.scss"
    ],
....
....
....

SweetAlert2 is a JavaScript library that provides beautiful and customizable alert, confirmation, and prompt dialogs for web applications. It is an upgraded version of the original SweetAlert library and offers a more modern and enhanced user experience.

Some key features of SweetAlert2 include:

Customizable appearance: SweetAlert2 allows you to customize the appearance of the dialogs by providing various options for styling, including buttons, icons, and animation effects. You can customize the colors, fonts, and other visual aspects to match the design of your application.

Multiple dialog types: It provides different types of dialogs such as alerts, confirmations, and prompts. Alerts display a simple message, confirmations ask the user for confirmation with options for “OK” and “Cancel,” and prompts allow the user to input a value.

Promise-based API: SweetAlert2 uses promises to handle user interactions. This makes it easier to work with asynchronous code and handle user responses. You can chain actions based on the user’s choice, making your code more readable and maintainable.

Support for callbacks and async/await: In addition to promises, SweetAlert2 supports traditional callback functions for handling user interactions. It also works seamlessly with async/await syntax, allowing you to write asynchronous code in a more synchronous style.

Easy integration: SweetAlert2 is designed to be easy to integrate into your existing web projects. It is compatible with popular JavaScript frameworks like React, Vue.js, and Angular, as well as plain HTML and JavaScript applications.

Register SweetAlert in App Component

In this step, we will register the required imperatives (package services) in order to invoke the notification messages via sweetalert2 package.

Here are the methods we need to define to maintain the order of precedence for opening the SweetAlert alert in angular on click event.

  • tinyAlert()
  • successNotification()
  • alertConfirmation()

Place the given below code in app/src/app.component.ts file.

import { Component, OnInit } from '@angular/core';
import Swal from 'sweetalert2';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
  ngOnInit() {
    console.log('Life Cyle Hook with spontaneous response.');
  }

  tinyAlert() {
    Swal.fire('Hey there!');
  }

  successNotification() {
    Swal.fire('Hi', 'We have been informed!', 'success');
  }

  alertConfirmation() {
    Swal.fire({
      title: 'Are you sure?',
      text: 'This process is irreversible.',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Yes, go ahead.',
      cancelButtonText: 'No, let me think',
    }).then((result) => {
      if (result.value) {
        Swal.fire('Removed!', 'Product removed successfully.', 'success');
      } else if (result.dismiss === Swal.DismissReason.cancel) {
        Swal.fire('Cancelled', 'Product still in our database.)', 'error');
      }
    });
  }
}

Display Notification

In this last step, we will spontaneously Display Alert and Notification Popup in Angular with SweetAlert library and the custom methods that we developed in the previous step.

Place the given below code in app/src/app.component.html file.

<button (click)="tinyAlert()">Simple Notification</button>

<button (click)="successNotification()">Sucess Notification</button>

<button (click)="alertConfirmation()">Show me Confirmation</button>

Run Development Server

Use the following command to start the angular application:

ng serve --open

Above command opens your app automatically on the browser, then the following output on your browser screen after clicking on any of the buttons.

Sweetalert2 in Angular

Angular Sweetalert2

Angular Notification with Sweetalert2

Conclusion

Eventually, we have placed everything at its place. In this tutorial, we have discussed foundational steps to integrate and to use sweetalert2 library in Angular. I am sure you would have comprehended the entire process by now.

We developed three essential alert boxes to notify users from absolute zero. i hope you have assimilated everything with your discretion that i explained in this tutorial. It will help you elevate your skills in Angular and SweetAlert2.

Be helpful to others by sharing this tutorial, if found any error by my recklessness then do inform me here.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.