Hello Devs,
In this tutorial, we are going to learn how to use sweetalert2 in angular 9.
Sweetalert2 is js library that provide a beautiful alert and confirm box. You can easily customize it too.
Follow this step by step guide given below:
Create New App
ng new ngSweetAlert
Install Npm Packages
npm install --save sweetalert2
angular.json
....
"styles": [
"src/styles.css",
"node_modules/sweetalert2/src/sweetalert2.scss"
],
....
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 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'
)
}
})
}
}
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.