Angular 13 Sweetalert2 Example

Angular 13 sweetalert example; Through this tutorial, i am going to show you how to use sweetalert or sweetalert2 in angular 13 apps.

Angular 13 Sweetalert2 Example

Use the below given steps to integrate sweetalert in agnular 13 apps:

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

Step 1 – Create New Angular App

Run the following command on command prompt to install angular app:

ng new my-new-app

Step 2 – Install Sweetalert Npm Packages

Run the following command on command prompt to install sweetalert2 npm package:

npm install --save sweetalert2

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

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

Step 3 – Implement Sweetalert on View File

Go to src/app/app.component.html and update the following code into it:

<h1>Angular 13 Sweetalert2 Examples - Laratutorials.com</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 the 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';
  
@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 succesfully!', '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 5 – Start Angular App

Run the following commands on command prompt to start angular app:

ng serve

php -S localhost:8001

Recommended Angular Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.