Angular 12 Sweetalert2 Tutorial with Example

Angular 12 ngx-sweetalert2 example. In this tutorial, i am going to show you how to integrate and use sweetalert or sweetalert2 in angular 12 app for displaying sweetalert msg using ngx-sweetalert2.

SweetAlert is a method to customize alerts in your applications, websites and games. It allows the user to change it with a standard JavaScript button. It is a standalone library with no dependencies and is composed of a JavaScript file plus a CSS file.

Integrate Sweetalert In Angular 12 App

  • Step 1 – Create New Angular App
  • Step 2 – Install Npm Packages
  • Step 3 – Add Code on View File
  • Step 4 – Add Code On Component ts File
  • Step 5 – Start Angular App

Step 1 – Create New Angular App

Execute the following command on terminal to install angular app:

ng new my-new-app

Step 2 – Install Npm Packages

Istall sweetalert2 npm package for sweetalert beautiful alert in angular. so let’s run both command:

npm install --save sweetalert2

Then, add css file on angular.json file as like following:


"styles": [

Step 3 – Add Code on View File

Ceate simple three buttons for displaying sweert alert message like success, error, warning and alert messsages So, visit src/app/app.component.html and update the following code into it:

<h1>Angular 11 Sweetalert2 Examples -</h1>
<button (click)="simpleAlert()">Simple Alert</button>
<button (click)="alertWithSuccess()">Alert with Success</button>
<button (click)="confirmBox()">Confirm Box</button>

Step 4 – Add Code On Component ts File

Go to src/app directory and open app.component.ts. Then add the following code into component.ts file:

import { Component, OnInit } from '@angular/core';
import Swal from 'sweetalert2/dist/sweetalert2.js';
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
export class AppComponent implements OnInit {
  name = 'Angular';
    console.log('This is init method');
  simpleAlert(){'Hello world!');
  alertWithSuccess(){'Thank you...', 'You submitted succesfully!', 'success')
      title: 'Are you sure want to remove?',
      text: 'You will not be able to recover this file!',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Yes, delete it!',
      cancelButtonText: 'No, keep it'
    }).then((result) => {
      if (result.value) {
          'Your imaginary file has been deleted.',
      } else if (result.dismiss === Swal.DismissReason.cancel) {
          'Your imaginary file is safe :)',

Step 5 – Start Angular App

Execute the following commands on terminal to start angular app:

ng serve

Recommended Angular Tutorials

Be First to Comment

Leave a Reply

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