18

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">
Limon Monte
  • 44,025
  • 43
  • 163
  • 189
Akash Rao
  • 890
  • 3
  • 12
  • 23

6 Answers6

22

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/sweetalert2@4.0.15/dist/sweetalert2.min.css">

<script src="https://npmcdn.com/sweetalert2@4.0.15/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.

Sampath
  • 50,641
  • 40
  • 250
  • 357
user1501382
  • 1,035
  • 13
  • 16
11

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"
        ],
Velu S Gautam
  • 657
  • 7
  • 16
  • 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? – Firanto Aug 25 '17 at 13:01
  • 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. – Velu S Gautam Aug 30 '17 at 04:19
  • 2
    Statement `import swal from 'swal';` didn't worked for me. Instead I used `import swal from 'sweetalert2';` – ranjeet8082 Oct 12 '17 at 09:07
  • 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. (platform-browser.js:993) a – Tarun Nagpal Jun 22 '19 at 13:49
  • this will not work . it should be **import Swal from 'sweetalert2';** – pankaj kumar Jan 05 '21 at 11:42
8

@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!

Morgan Touverey Quilling
  • 3,824
  • 4
  • 27
  • 37
6

npm install sweetalert2

You can try:

import swal from 'sweetalert2'; 

swal.fire('Hello world!')//fire
Samer Abu Gahgah
  • 693
  • 1
  • 11
  • 18
user11373723
  • 61
  • 1
  • 1
1

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

Uzzal Prasad
  • 105
  • 9
0

this is how i use it on my projects

npm install sweetalert2

after installing add swal to window

window.swal = require('sweetalert2');

thats all. if you are having problem with css, just import the scss file

@import "node_modules/sweetalert2/src/sweetalert2";

or include the css file from the node_module directory

Canaan Etai
  • 2,144
  • 2
  • 18
  • 15