Angular 10 Popup Notification with SweetAlert2 Example

Last updated on by Digamber
This tutorial explains to you how to show an alert or popup notification in Angular 10 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 sweetalert example. If you want to provide information to your user from UX point of you, then this sweetalert angular example tutorial is going to be beneficial for you.

Angular SweetAlert Popup Notification Example

The sweetalert 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.

Plugin team did not show the single sign of recklessness while creating this plugin. If i talk about the popularity of this plugin, then it is being downloaded possibly 204,002 times per week, that tells a lot about their prudence and austerity itself.

Essentials

  • 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 Latest Angular CLI

Run the following command to install the latest version of Angular CLI (version 9+).

npm install -g @angular/cli@latest

Install Angular Application

Preferably, this step consist of installing a fresh angular 10 application on your development machine. Run the following command, answer some questions asked by angular CLI.

ng new angular-sweetalert-demo

? Would you like to add Angular routing? No
? Which stylesheet format would you like to use? 
  CSS 
❯ SCSS   [ https://sass-lang.com/documentation/syntax#scss                ] 
  Sass   [ https://sass-lang.com/documentation/syntax#the-indented-syntax ] 
  Less   [ http://lesscss.org                                             ] 
  Stylus [ http://stylus-lang.com 

You can opt for any styling format like SCSS, SASS or LESS for your project.

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

cd ng new angular-sweetalert-demo

Install SweetAlert2 in Angular 10

Install sweetalert2 npm package for displaying beautiful notifications and alert in angular 10. 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"
    ],
....
....
....

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/dist/sweetalert2.js';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

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>

Start Application

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

The Bottom Line

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.