Welcome folks today in this blog post we will be showing popup alert
messages in browser using sweetalert2
library using typescript. All the full source code of the application is shown below.
Get Started
In order to get started you need to initialize a new angular
project using the below command as shown below
ng new angularproject
After that you need to install the below library using the npm
command as shown below
npm i sweetalert2
After that you will see the below directory
structure of the angular app as shown below
After that you need to go to app.component.html
file and copy paste the following code
app.component.html
1 2 3 |
<button (click)="tinyAlert()">Simple Notification</button> <button (click)="successNotification()">Sucess Notification</button> <button (click)="alertConfirmation()">Show me Confirmation</button> |
As you can see we have three buttons
in which we can show three
types of notifications. And also we can bind three methods to all three buttons.
And now we need to go to app.component.ts
file and copy paste the following code
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import { Component, OnInit } from '@angular/core'; import Swal from 'sweetalert2'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit { 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'); } }); } } |
As you can see we are importing the sweetalert2
library at the top and then we are using the Swal.fire()
method to show the popup alert
messages. Here we are providing the title
of the alert window. And then we are providing the icon
as well which can be for success
,info and error
. And then we are also providing the showCancelButton
to show the cancel button.