How to use sweetalert2 in angular2

40,844

Solution 1

Solution given by @yurzui is the only worked with angular2. I tried almost everything. Plunker may go away. i'm putting it here for others:

Plunker

1) Add these css and js on top of your index.html

<link rel="stylesheet" href="https://npmcdn.com/[email protected]/dist/sweetalert2.min.css">

<script src="https://npmcdn.com/[email protected]/dist/sweetalert2.min.js"></script>

2) Add this line to the component where you want to use swal.

declare var swal: any;

After these changes my swal namespace is available and i'm able to use it's features.

I did not import any ng2-sweelalert2 or any other module.

Solution 2

NPM install SweetAlert2

npm install sweetalert2

You can add

import swal from 'swal'; 
//import swal from 'sweetalert2'; --if above one didn't work

in your component and you can start using like in your component.

swal({
  title: 'Error!',
  text: 'Do you want to continue',
  type: 'error',
  confirmButtonText: 'Cool'
})

You can use fat arrow to maintain this.

deleteStaff(staffId: number) {
     swal({
          type:'warning',
          title: 'Are you sure to Delete Staff?',
          text: 'You will not be able to recover the data of Staff',
          showCancelButton: true,
          confirmButtonColor: '#049F0C',
          cancelButtonColor:'#ff0000',
          confirmButtonText: 'Yes, delete it!',
          cancelButtonText: 'No, keep it'
        }).then(() => {
        this.dataService.deleteStaff(staffId).subscribe(
          data => {
            if (data.hasOwnProperty('error')) {
              this.alertService.error(data.error);
            } else if (data.status) {
              swal({
                type:'success',
                title: 'Deleted!',
                text: 'The Staff has been deleted.',              
              })
            }
          }, error => {
            this.alertService.error(error);
          });
        }, (dismiss) => {
          // dismiss can be 'overlay', 'cancel', 'close', 'esc', 'timer'
          if (dismiss === 'cancel') {
            swal({
              type:'info',
              title: 'Cancelled',
              text: 'Your Staff file is safe :)'
            })
          }
        });
    }

In angular-cli.json

"styles": [
            "../node_modules/sweetalert2/dist/sweetalert2.css"

        ],
"scripts": [
            "../node_modules/sweetalert2/dist/sweetalert2.js"
        ],

Solution 3

@user1501382's solution is very handy sometimes for pure-JavaScript packages that don't have type definitions, for example, and that was the case for SweetAlert2, until a few weeks ago. Also, using the global swal variable isn't very neat and you can do much better.

Now that SweetAlert2 has type defintions, you can do:

import swal from 'sweetalert2';

swal({ ... }); // then use it normally and enjoy type-safety!

Also import SweetAlert's CSS file, via a <link> or whatever. When you use a module bundler like Webpack and you have css-loader and style-loader configured, you can also do something like:

import 'sweetalert2/dist/sweetalert2.css';

Edit: this should not be necessary since SweetAlert2 v.7.0.0, which bundles the CSS build into the JavaScript, and injects the styles in the page at runtime.

Also, I'll let you discover my library, that provides Angular-esque utilities to use SweetAlert2 with ease and class: sweetalert2/ngx-sweetalert2 (it is now the official SweetAlert2 integration for Angular)

Give it a try!

Solution 4

npm install sweetalert2

You can try:

import swal from 'sweetalert2'; 

swal.fire('Hello world!')//fire

Solution 5

First, install sweetalert2using npm. Then import Swal from 'sweetalert2'

In app.component.html

<input type="button" value="Show Toast" class="btn btn-primary" (click)="showToast()"/>

<input type="button" value="Show Message" class="btn btn-primary" (click)="showMessage()"/>

In app.component.ts

showToast(){
Swal.fire({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000, title: 'Success!', text: 'Sweet Alert Toast', icon: 'success', });
  }

  showMessage(){
    Swal.fire({ text: 'Hello!', icon: 'success'});
  }

stackblitz

Share:
40,844

Related videos on Youtube

Akash Rao
Author by

Akash Rao

Hi, I am a front end developer having 3+ years of experience in web technologies like HTML, CSS, Javascript, Jquery, Angular 2 and Ionic 2.I use stackoverflow very often and love this. :)

Updated on August 22, 2020

Comments

  • Akash Rao
    Akash Rao almost 4 years

    Getting this error after npm start in angular project.

    app/app.component.ts(12,7): error TS2304: Cannot find name 'swal'. app/app.component.ts(21,7): error TS2304: Cannot find name 'swal'.

    I created an angular project. Inside app.component.ts I added sweet alert code

    export class AppComponent {
    deleteRow() {
          swal({
          title: 'Are you sure?',
          text: "You won't be able to revert this!",
          type: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: 'Yes, delete it!'
        }).then(function() {
          swal(
            'Deleted!',
            'Your file has been deleted.',
            'success'
          );
        })
      }
    }
    

    I did

    npm install sweetalert2 --save 
    

    and also added the path in index.html

    <script src="node_modules/sweetalert2/dist/sweetalert2.min.js"></script>
    <link rel="stylesheet" type="text/css" href="node_modules/sweetalert2/dist/sweetalert2.css">
    
  • Firanto
    Firanto almost 7 years
    Where can I find angular-cli.json? I can't find them in codes generated by dotnet core. I also cannot find it on Angular 2 tutorial. By the way, the genererated codes use webpack. Is there any way to define this css and js on it?
  • Velu S Gautam
    Velu S Gautam almost 7 years
    angular-cli.json comes with the angular-cli installation. You can either statically define the css and js your application or copy the above files to your css and js folder, but you need to do that next time when you do npm update.
  • ranjeet8082
    ranjeet8082 over 6 years
    Statement import swal from 'swal'; didn't worked for me. Instead I used import swal from 'sweetalert2';
  • Tarun Nagpal
    Tarun Nagpal about 5 years
    WorkersComponent.html:33 ERROR TypeError: Cannot read property 'constructor' of undefined at SweetAlert (sweetalert2.js:2741) at WorkersComponent.deleteRecord (workers.component.ts:30) at Object.eval [as handleEvent] (WorkersComponent.html:33) at handleEvent (core.js:23107) at callWithDebugContext (core.js:24177) at Object.debugHandleEvent [as handleEvent] (core.js:23904) at dispatchEvent (core.js:20556) at core.js:21003 at HTMLButtonElement.<anonymous> (platform-browser.js:993) a
  • pankaj kumar
    pankaj kumar over 3 years
    this will not work . it should be import Swal from 'sweetalert2';