How to use sweetalert2 in angular2

2019-03-18 14:09发布

问题:

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

回答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/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.



回答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"
        ],


回答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!



回答4:

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