7

I have a method inside a typescript class that just looks like this

    var confirmation = confirm("Run Agent Job?");
    if (confirmation) {
        console.log('yes');
    } else {
        console.log('no');
    }

I'm trying to convert this to use Sweet Alert, so inside the method I just put this. But Typescript doesn't recognize this It throws a Cannot find name swal

swal("hello");

I have imported sweet alert as follows

<link href="~/Content/css/sweetalert.css" rel="stylesheet" />
<script src="~/Scripts/sweetalert.min.js"></script>

What am I doing wrong? If I try to use swal() in just a plain *.js file, it'll work fine. It's only when it's in a *.ts file.

5 Answers5

7

Typescript

I got it to work with typescript the following way. In the top of your .ts file use:

import * as swal from 'sweetalert';

Then use the function like this

swal({
  title: "Are you sure?",
  text: "You will not be able to undo this action",
  type: "warning",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "Yes, delete it!",
  closeOnConfirm: true
},
confirmed => {
   if(confirmed) {
       // Do what ever when the user click on the 'Yes, delete it' button
   }
});

You can find more examples in the docs.

Installation via npm and typings

I installed the sweetalert package the via npm

npm install sweetalert --save

and the typings

// the old way
typings install dt~sweetalert --save --global 

// new way
npm install --save @types/sweetalert

After this, make sure you have included the js and the css file in your index.html.

If you get the following error

swal(..) is not a function

then you have not included the js file properly.

For aurelia CLI users

You can add the following to your aurelia.json.

      {
        "name": "sweetalert",
        "path": "../node_modules/sweetalert",
        "main": "dist/sweetalert.min",
        "resources": [
          "dist/sweetalert.css"
        ]
      },

and in app.html use

<require from="sweetalert/dist/sweetalert.css"></require>
Tom Aalbers
  • 4,574
  • 5
  • 29
  • 51
  • 1
    The resources part in aurelia.json configures the CLI to put it in the bundle via requirejs's text plugin, but it is not automatically loaded as valid CSS at runtime. To use it with Aurelia-CLI's build-in loading mechanism, you need to require it in an Aurelia HTML template (probably app.html). In your example adding `` should work fine. Of course you cannot not require it in index.html, since it is loaded before the framework's boostrapping process and requirejs is also not loaded yet. – MannikJ Nov 29 '16 at 16:12
  • Note that `npm install --save @types/sweetalert` is no longer necessary because sweetalert now provides its own type definitions. – Thane Brimhall Nov 20 '18 at 05:02
  • I tried as described in first part: 1) TS file: `import swal from 'sweetalert'; swall("Hello");` 2). JS file: almost the same: `import ....` 3). index.html: `` But then when I start this page, I get: Uncaught TypeError: Failed to resolve module specifier "sweetalert". Relative references must start with either "/", "./", or "../". If I manually delete import from js file, it works. What am I missing? – ramijan Aug 19 '21 at 16:08
3

We can't use the function swal({...}) but we can use the second overload of Swal.fire({...}) method, casting the parameters to SweetAlertOptions... My code looks like this...

import Swal, {SweetAlertOptions} from 'sweetalert2';
Swal.fire({
        title: 'Are you sure?',
        text: 'You won\'t be able to revert this!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
      } as SweetAlertOptions).then((result) => {
        if (result.value) {
           //Do something here
        }
      });
Dharman
  • 30,962
  • 25
  • 85
  • 135
2

In addition @TomAalbers answer, there is a bug with Angular 5 and sweetalert which will also cause this error. If you are using angular 5, then you can't use:

import * as swal from 'sweetalert';

Instead you need this ugly work around:

import * as _swal from 'sweetalert';
import { SweetAlert } from 'sweetalert/typings/core';
const swal: SweetAlert = _swal as any;

Credit where it's due

This seems to be related to this bug in Angular CLI where default exports are handled differently in dev. They seem to have fixed it in v6.0.0-beta.4

Zze
  • 18,229
  • 13
  • 85
  • 118
0

You have to import this in top of your class:

import Swal from 'sweetalert2/dist/sweetalert2.js'
import 'sweetalert2/src/sweetalert2.scss'

and don´t forget to add this in your app.module.ts file

enter image description here

trincot
  • 317,000
  • 35
  • 244
  • 286
  • It's better to paste the code as text instead of an image. Images could be lost if some is coming here after years – Aman B Dec 22 '18 at 17:28
0

Typescript

In this way working for me, I am using angular 7 and sweetalert2.

Installation

  • npm install sweetalert2

OR

  • <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>

.ts

   openDateDialog() {
    swal({
      html: '<h1>Sweet2 with angularJS</h1>',
      showConfirmButton: true,
      customClass: 'swal2-overflow'
    }).then(function(isConfirm){ if (isConfirm) {
      console.log('confirm, do any function');
    } else {
      swal("Cancelled", "Your imaginary file is safe :)", "error");
    }});
  }

.html

<mat-select [(value)]="dateselected" (selectionChange)="onChangeDate(dateselected)">
            <mat-option value="0" (click)="openDateDialog()" >Sur-Mesure</mat-option>
            <mat-option value="thisMonth" >Ce mois-ci</mat-option>
            <mat-option value="all" >Toute la période</mat-option>
          </mat-select>
Ankit Singh
  • 327
  • 4
  • 12