How to use sweetalert2 in angular2

Akash Rao picture Akash Rao · Jul 30, 2016 · Viewed 36.5k times · Source

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">

Answer

user1501382 picture user1501382 · Oct 6, 2016

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.