This write-up describes how to implement sweet alert in Angular.

Very first step is to create a Angular project.

Step 1- Create Project

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

npm install -g @angular/cli@latest

Run below command to create new project

ng new AngularAppwithSweetAlertDemo

Then, run below command and go to your project directory.

cd AngularAppwithSweetAlertDemo

Step 2- Install SweetAlert2

Run below command to Install SweetAlert2 in your project.

npm install sweetalert2

Open your Project and go to angular.json file. Then copy and paste the below line of code there.

"styles": [

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

Your angular.json file will look like below.

Step 3- Register SweetAlert in App component

Copy and paste below code in app.component.ts file.

import { Component } from '@angular/core';
import Swal from 'sweetalert2/dist/sweetalert2.js';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'StratisFullNodeWebApp';
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'
)
}
})
}
}

Step 4- Implementation

Open the corresponding component.ts for which you need to implement the sweet alert. In the click event of your component.ts class write below code to implement sweet alert.

For Success:

Swal.fire('Successful', 'Full Node Connection successful', 'info');

For Error:

Swal.fire('Oops…', 'Something went wrong!, Please contact your administrator', 'error');

Sample example of componet.ts code

SaveItem() {   
    this.itemService.SaveItem(this.item).subscribe((response: any) => {     
      if (response.outputs) {
        this.items = response.outputs;    
		Swal.fire('Successful', 'Item saved successfully', 'info');
      } else {
       Swal.fire('Oops...', 'Something went wrong!, Please contact your administrator', 'error');
       
        (error: any) => {
          console.log(error);
        }
      }
    });
  }

sample html page example

<button (click)="SaveItem()">Save Item</button>

In this way, you can implement SweetAlert2 in your angular application.

Leave a Reply

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