Hello Devs,

In this tutorial, we are going to learn how to use sweetalert2 in angular 10.

Given below is the simple example of sweetalert2 example in angular 10.

Follow this step by step guide given below:




Step 1: 


Create New App 

ng new ngSweetAlert



Step 2: 


Install Npm Packages 

npm install --save sweetalert2

angular.json

....

"styles": [

      "src/styles.css",

      "node_modules/sweetalert2/src/sweetalert2.scss"

    ],

....



Step 3:

 

Update Component ts File src/app/app.component.ts

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

import Swal from 'sweetalert2/dist/sweetalert2.js';

  

@Component({

  selector: 'my-app',

  templateUrl: './app.component.html',

  styleUrls: [ './app.component.css' ]

})

export class AppComponent implements OnInit {

  name = 'Angular';

  

  ngOnInit(){

    console.log('This is init method');

  }

  

  simpleAlert(){

    Swal.fire('Hello world!');

  }

  

  alertWithSuccess(){

    Swal.fire('Thank you...', 'You submitted successfully!', 'success')

  }

  

  confirmBox(){

    Swal.fire({

      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) {

        Swal.fire(

          'Deleted!',

          'Your imaginary file has been deleted.',

          'success'

        )

      } else if (result.dismiss === Swal.DismissReason.cancel) {

        Swal.fire(

          'Cancelled',

          'Your imaginary file is safe :)',

          'error'

        )

      }

    })

  }

}



Step 4:


Update HTML File src/app/app.component.html

<h1>Angular Sweetalert2 Examples - Rathorji.in</h1>

  

<button (click)="simpleAlert()">Simple Alert</button>

<button (click)="alertWithSuccess()">Alert with Success</button>

<button (click)="confirmBox()">Confirm Box</button>


Run this command:

ng serve


I hope this example helps you.