How To Use SweetAlert In Angular


In this article we will learn how to use SweetAlert in Angular. SweetAlert is use to display messages.

Create a Project:

First, open visual studio code & create a new project by typing below command in terminal.

ng new sweetAlertDemo

Install Packages:

Install bootstrap & sweetAlert step by step by using following command.

Install bootstrap:

npm install bootstrap --save

Install SweetAlert:

npm install sweetalert2

Now open the style.css file and add bootstrap file reference:

@import '~bootstrap/dist/css/bootstrap.min.css';

After that open the index.html file and add following line to it:

<script src=""></script>

Add below code to app.component.html file.

<div class="row">  
    <div class="col-sm-12 btn btn-primary">  
      Angular Sweetalert Demo  
  <div style="padding: 5px;margin: 5px;">  
    <button class="btn btn-info" style="margin-right: 10px;margin-left: 10px;"(click)="simpleAlert()">Simple Alert</button>  
    <button class="btn btn-success" style="margin-right: 10px;margin-left: 10px;" (click)="alertWithSuccess()">Alert with Success</button>  
    <button class="btn btn-primary" style="margin-right: 10px;margin-left: 10px;" (click)="confirmBox()">Confirm Box</button>  
    <button class="btn btn-danger" style="margin-right: 10px;margin-left: 10px;" (click)="erroalert()">Error Alert</button>  
    <button class="btn btn-warning" style="margin-right: 10px;margin-left: 10px;" (click)="topend()">Top End</button>  

Copy following code and paste to app.component.ts file.

import { Component } from '@angular/core';
import Swal from 'sweetalert2';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  title = 'sweetalert';
  ngOnInit() {


  simpleAlert() {'Hello Angular');

  alertWithSuccess() {'Thank you...', 'You submitted succesfully!', 'success')
  erroalert() {{
      icon: 'error',
      title: 'Oops...',
      text: 'Something went wrong!',
      footer: '<a href>Why do I have this issue?</a>'
  topend() {{
      position: 'top-end',
      icon: 'success',
      title: 'Your work has been saved',
      showConfirmButton: false,
      timer: 1500
  confirmBox() {{
      title: 'Are you sure want to delete?',
      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) {
          'Your imaginary file has been deleted.',
      } else if (result.dismiss === Swal.DismissReason.cancel) {
          'Your imaginary file is safe :)',


Submit a Comment

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


Select Categories