Coder Social home page Coder Social logo

sweetalert2 / ngx-sweetalert2 Goto Github PK

View Code? Open in Web Editor NEW
641.0 14.0 90.0 2.77 MB

Declarative, reactive, and template-driven SweetAlert2 integration for Angular

License: MIT License

TypeScript 88.40% JavaScript 4.57% CSS 0.19% HTML 6.84%
angular sweetalert sweetalert2 dialog modal alert ux

ngx-sweetalert2's Introduction

SweetAlert2

@sweetalert2/ngx-sweetalert2

Official SweetAlert2 integration for Angular

npm version Build Status license


This is not a regular API wrapper for SweetAlert (which already works very well alone), it intends to provide Angular-esque utilities on top of it.

👉 Before posting an issue, please check that the problem isn't on SweetAlert's side.


Quick start

Wiki recipes


📦 Installation & Usage

  1. Install ngx-sweetalert2 and sweetalert2 via the npm registry:
npm install sweetalert2 @sweetalert2/ngx-sweetalert2

⏫ Always upgrade SweetAlert2 when you upgrade ngx-sweetalert2. The latter is statically linked with SweetAlert2's type definitions.

Angular and SweetAlert2 versions compatibility table

Angular version Latest compatible version range Required SweetAlert2 version range
Angular 14+ @sweetalert2/ngx-sweetalert2@^12.0.0 (current) sweetalert2@^11.0.0
Angular 12, 13 @sweetalert2/ngx-sweetalert2@^11.0.0 sweetalert2@^11.0.0
Angular 9 to 11 @sweetalert2/ngx-sweetalert2@~9.0.0 sweetalert2@^10.8.0
Angular 8 @sweetalert2/ngx-sweetalert2@~7.3.0 (:warning: NOT ~7.4.0, broken AoT metadata) sweetalert2@^9.7.0
Angular 7 @sweetalert2/ngx-sweetalert2@^5.1.0 sweetalert2@^8.5.0
Angular 6 @sweetalert2/ngx-sweetalert2@^5.1.0 sweetalert2@^8.5.0
Angular 5 @sweetalert2/ngx-sweetalert2@^5.1.0 sweetalert2@^8.5.0
Angular 4 @toverux/ngx-sweetalert2@^3.4.0 sweetalert2@^7.15.1
Angular 2 Try Angular 4 versions requirements, or older versions like @toverux/ngsweetalert2 unknown
  1. Import the module:
import { SweetAlert2Module } from '@sweetalert2/ngx-sweetalert2';

@NgModule({
    //=> Basic usage (forRoot can also take options, see the wiki)
    imports: [SweetAlert2Module.forRoot()],

    //=> In submodules only:
    imports: [SweetAlert2Module],

    //=> In submodules only, overriding options from your root module:
    imports: [SweetAlert2Module.forChild({ /* options */ })]
})
export class AppModule {
}

That's it! By default, SweetAlert2 will be lazy-loaded, only when needed, from your local dependency of sweetalert2, using the import() syntax under the hood.

🔗 API

SwalDirective

Add the [swal] attribute to an element to show a simple modal when that element is clicked.

To define the modal contents, you can pass a SweetAlertOptions (provided by sweetalert2) object, or a simple array of strings, of format [title: string, text: string (, icon: string)].

A simple dialog:

<button [swal]="['Oops!', 'This is not implemented yet :/', 'warning']">
  Do it!
</button>

More advanced, with text input, confirmation, denial and dismissal handling:

<button
  [swal]="{ title: 'Save file as...', input: 'text', showDenyButton: true, denyButtonText: 'Don\'t save', showCancelButton: true }"
  (confirm)="saveFile($event)"
  (deny)="handleDenial()"
  (dismiss)="handleDismiss($event)">

  Save
</button>
export class MyComponent {
  public saveFile(fileName: string): void {
    // ... save file
  }

  public handleDenial(): void {
      // ... don't save file and quit
  }

  public handleDismiss(dismissMethod: string): void {
    // dismissMethod can be 'cancel', 'overlay', 'close', and 'timer'
    // ... do something
  }
}

The directive can also take a reference to a <swal> component for more advanced use cases:

<button [swal]="deleteSwal" (confirm)="deleteFile(file)">
  Delete {{ file.name }}
</button>

<swal #deleteSwal title="Delete {{ file.name }}?" etc></swal>

SwalComponent

The library also provides a component, that can be useful for advanced use cases, or when you [swal] has too many options.

The component also allows you to use Angular dynamic templates inside the SweetAlert (see the *swalPortal directive for that).

Simple example:

<swal
  #deleteSwal
  title="Delete {{ file.name }}?"
  text="This cannot be undone"
  icon="question"
  [showCancelButton]="true"
  [focusCancel]="true"
  (confirm)="deleteFile(file)">
</swal>

With [swal]:
<button [swal]="deleteSwal">Delete {{ file.name }}</button>

Or DIY:
<button (click)="deleteSwal.fire()">Delete {{ file.name }}</button>

You can access the dialog from your TypeScript code-behind like this:

class MyComponent {
  @ViewChild('deleteSwal')
  public readonly deleteSwal!: SwalComponent;
}

You can pass native SweetAlert2 options via the swalOptions input, just in the case you need that:

<swal [swalOptions]="{ confirmButtonText: 'I understand' }"></swal>

By the way: every "special" option, like swalOptions, that are not native options from SweetAlert2, are prefixed with swal.

You can catch other modal lifecycle events than (confirm), (deny) or (cancel):

<swal
  (willOpen)="swalWillOpen($event)"
  (didOpen)="swalDidOpen($event)"
  (didRender)="swalDidRender($event)"
  (willClose)="swalWillClose($event)"
  (didClose)="swalDidClose()"
  (didDestroy)="swalDidDestroy()">
</swal>
export class MyComponent {
    public swalWillOpen(event: WillOpenEvent): void {
      // Most events (those using $event in the example above) will let you access the modal native DOM node, like this:
      console.log(event.modalElement);
    }
}

SwalPortalDirective

The *swalPortal structural directive lets you use Angular dynamic templates inside SweetAlerts.

The name "portal" is inspired by React or Angular CDK portals. The directive will replace certain parts of the modal (aka. swal targets) with embedded Angular views.

This allows you to have data binding, change detection, and use every feature of the Angular template syntax you want, just like if the SweetAlert was a normal Angular component (it's not at all).

<swal title="SweetAlert2 Timer">
  <div *swalPortal class="alert alert-info">
    <strong>{{ elapsedSeconds }}</strong> seconds elapsed since the modal was opened.
  </div>
</swal>

Using a structural directives allows us to take your content as a template, instantiate it lazily when needed (i.e. when the modal is shown), and putting it in a native DOM element that is originally outside the scope of your Angular app.

In this example we set the main content of the modal, where the text property is usually rendered when SweetAlert2 is in charge. You can also target the title, the footer, or even the confirm button, and more!

You just have to change the target of the portal (content is the default target). First, inject this little service in your component:

import { SwalPortalTargets } from '@sweetalert2/ngx-sweetalert2';

export class MyComponent {
  public constructor(public readonly swalTargets: SwalPortalTargets) {
  }
}

Then, set the appropriate target as the value of *swalPortal, here using two portals, the first one targeting the modal's content (this is the default), and the other one targeting the confirm button text.

<swal title="Fill the form, rapidly" (confirm)="sendForm(myForm.value)">
  <!-- This form will be displayed as the alert main content
       Targets the alert's main content zone by default -->
  <form *swalPortal [formControl]="myForm">
    ...
  </form>

  <!-- This targets the confirm button's inner content
       Notice the usage of ng-container to avoid creating an useless DOM element inside the button -->
  <ng-container *swalPortal="swalTargets.confirmButton">
    Send ({{ secondsLeft }} seconds left)
  </ng-container>
</swal>

We have the following targets: closeButton, title, content, actions, confirmButton, cancelButton, and footer.

These targets are mostly provided by SweetAlert2 and made available in the right format for swal portals by this library, but you can also make your own if you need to (take inspiration from the original service source). Those are just variables containing a function that returns a modal DOM element, not magic. The magic is inside the directive ;)

ngx-sweetalert2's People

Contributors

acegilz avatar cassmtnr avatar depfu[bot] avatar fklingler avatar fscherwi avatar gaykevin avatar imgbot[bot] avatar kjra1707 avatar limonte avatar rafaelss95 avatar renovate[bot] avatar toverux avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ngx-sweetalert2's Issues

Error: Template parse errors: 'swal' is not a known element:

I get the following error when I try to use this library:

Error: Uncaught (in promise): Error: Template parse errors:
'swal' is not a known element:
If 'swal' is an Angular component, then verify that it is part of this module.
To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. (" <form name="form" (ngSubmit)="f.form.valid && login()" #f="ngForm" novalidate>
[ERROR ->]<swal #dialog >


<span class=""): ng:///PagesModule/LoginComponent.html@10:16
syntaxError@webpack-internal:///../../../compiler/@angular/compiler.es5.js:1913:34
TemplateParser.prototype.parse@webpack-internal:///../../../compiler/@angular/compiler.es5.js:13010:19
JitCompiler.prototype._compileTemplate@webpack-internal:///../../../compiler/@angular/compiler.es5.js:27213:18
JitCompiler.prototype._compileComponents/<@webpack-internal:///../../../compiler/@angular/compiler.es5.js:27132:56
JitCompiler.prototype._compileComponents@webpack-internal:///../../../compiler/@angular/compiler.es5.js:27132:9
JitCompiler.prototype._compileModuleAndComponents/<@webpack-internal:///../../../compiler/@angular/compiler.es5.js:27019:13
then@webpack-internal:///../../../compiler/@angular/compiler.es5.js:1902:133
JitCompiler.prototype._compileModuleAndComponents@webpack-internal:///../../../compiler/@angular/compiler.es5.js:27018:16
JitCompiler.prototype.compileModuleAsync@webpack-internal:///../../../compiler/@angular/compiler.es5.js:26947:32
ModuleBoundCompiler.prototype.compileModuleAsync@webpack-internal:///../../../compiler/@angular/compiler.es5.js:27347:16
SystemJsNgModuleLoader.prototype.loadAndCompile/<@webpack-internal:///../../../core/@angular/core.es5.js:5862:44
ZoneDelegate.prototype.invoke@webpack-internal:///../../../../zone.js/dist/zone.js:392:17
onInvoke@webpack-internal:///../../../core/@angular/core.es5.js:4090:24
ZoneDelegate.prototype.invoke@webpack-internal:///../../../../zone.js/dist/zone.js:391:17
Zone.prototype.run@webpack-internal:///../../../../zone.js/dist/zone.js:142:24
scheduleResolveOrReject/<@webpack-internal:///../../../../zone.js/dist/zone.js:873:52
ZoneDelegate.prototype.invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:425:17
onInvokeTask@webpack-internal:///../../../core/@angular/core.es5.js:4081:24
ZoneDelegate.prototype.invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:424:17
Zone.prototype.runTask@webpack-internal:///../../../../zone.js/dist/zone.js:192:28
drainMicroTaskQueue@webpack-internal:///../../../../zone.js/dist/zone.js:602:25
ZoneTask.invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:503:21
invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:1540:9
globalZoneAwareCallback@webpack-internal:///../../../../zone.js/dist/zone.js:1566:17
Stack trace:
resolvePromise@webpack-internal:///../../../../zone.js/dist/zone.js:824:31
resolvePromise@webpack-internal:///../../../../zone.js/dist/zone.js:795:17
scheduleResolveOrReject/<@webpack-internal:///../../../../zone.js/dist/zone.js:873:17
ZoneDelegate.prototype.invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:425:17
onInvokeTask@webpack-internal:///../../../core/@angular/core.es5.js:4081:24
ZoneDelegate.prototype.invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:424:17
Zone.prototype.runTask@webpack-internal:///../../../../zone.js/dist/zone.js:192:28
drainMicroTaskQueue@webpack-internal:///../../../../zone.js/dist/zone.js:602:25
ZoneTask.invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:503:21
invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:1540:9
globalZoneAwareCallback@webpack-internal:///../../../../zone.js/dist/zone.js:1566:17

Here is my package.json file:

{
"name": "@coreui/angular",
"version": "1.0.5",
"description": "Open Source Bootstrap Admin Template",
"author": "Łukasz Holeczek",
"homepage": "http://coreui.io",
"copyright": "Copyright 2017 creativeLabs Łukasz Holeczek",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~4.4.6",
"@angular/cdk": "^5.0.0-rc0",
"@angular/common": "~4.4.6",
"@angular/compiler": "~4.4.6",
"@angular/core": "~4.4.6",
"@angular/forms": "~4.4.6",
"@angular/http": "~4.4.6",
"@angular/material": "^5.0.0-rc0",
"@angular/platform-browser": "~4.4.6",
"@angular/platform-browser-dynamic": "~4.4.6",
"@angular/platform-server": "~4.4.6",
"@angular/router": "~4.4.6",
"@toverux/ngsweetalert2": "^2.0.1",
"angular2-notifications": "^0.7.8",
"bootstrap": "4.0.0-beta.2",
"chart.js": "2.7.1",
"core-js": "2.5.1",
"font-awesome": "^4.7.0",
"moment": "2.19.1",
"ng2-charts": "1.6.0",
"ngx-bootstrap": "1.9.3",
"rxjs": "5.5.2",
"simple-line-icons": "^2.4.1",
"sweetalert2": "^6.11.5",
"ts-helpers": "1.1.2",
"zone.js": "0.8.18"
},
"devDependencies": {
"@angular/cli": "1.5.0",
"@angular/compiler-cli": "^4.0.0",
"@angular/language-service": "^4.0.0",
"@types/jasmine": "~2.5.53",
"@types/jasminewd2": "~2.0.2",
"@types/node": "~6.0.60",
"codelyzer": "~3.0.1",
"jasmine-core": "2.8.0",
"jasmine-spec-reporter": "4.2.1",
"karma": "1.7.1",
"karma-chrome-launcher": "2.2.0",
"karma-cli": "1.0.1",
"karma-jasmine": "1.1.0",
"karma-jasmine-html-reporter": "0.2.2",
"karma-coverage-istanbul-reporter": "1.3.0",
"protractor": "~5.1.2",
"ts-node": "~3.0.4",
"tslint": "~5.3.2",
"typescript": "~2.3.3"
},
"engines": {
"node": ">= 6.9.0",
"npm": ">= 3.0.0"
}
}

My plunk: https://plnkr.co/edit/uFUaNSvOAjwsnperAZJ5?p=preview

Angular5 update?

The module does not seem to work on the angular 5 version, any update planed? Don't want to recode every dialogs haha

EDITED : My bad, working fine --'

Backdrop & toast do not exist in SweetAlertOptions

Repro:
npm install --save sweetalert2 @toverux/ngx-sweetalert2

@NgModule({
    imports: [SweetAlert2Module.forRoot()],
}

Error Log:

Failed to compile.
node_modules/@toverux/ngx-sweetalert2/swal.component.d.ts(26,33): error TS2339: Property 'backdrop' does not exist on type 'SweetAlertOptions'.
node_modules/@toverux/ngx-sweetalert2/swal.component.d.ts(27,30): error TS2339: Property 'toast' does not exist on type 'SweetAlertOptions'.

Error in angular 5

hi,

I have angular 5, when install following you instructions show me this error message

ERROR in node_modules/sweetalert2/sweetalert2.d.ts(209,17): error TS2300: Duplicate identifier 'SweetAlertType'.
node_modules/sweetalert2/sweetalert2.d.ts(211,17): error TS2300: Duplicate identifier 'SweetAlertInputType'.
node_modules/sweetalert2/sweetalert2.d.ts(217,22): error TS2300: Duplicate identifier 'SweetAlertInputOptions'.
node_modules/sweetalert2/sweetalert2.d.ts(221,22): error TS2300: Duplicate identifier 'SweetAlertInputAttributes'.
node_modules/sweetalert2/sweetalert2.d.ts(678,5): error TS2300: Duplicate identifier 'default'.
src/assets/vendors/bower_components/sweetalert2/sweetalert2.d.ts(198,17): error TS2300: Duplicate identifier 'SweetAlertType'.

src/assets/vendors/bower_components/sweetalert2/sweetalert2.d.ts(200,17): error TS2300: Duplicate identifier 'SweetAlertInputType'.
src/assets/vendors/bower_components/sweetalert2/sweetalert2.d.ts(202,17): error TS2300: Duplicate identifier 'SweetAlertInputOptions'.
src/assets/vendors/bower_components/sweetalert2/sweetalert2.d.ts(204,17): error TS2300: Duplicate identifier 'SweetAlertInputAttributes'.
src/assets/vendors/bower_components/sweetalert2/sweetalert2.d.ts(232,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'html' must be of type 'string | JQ
uery', but here has type 'string'.
src/assets/vendors/bower_components/sweetalert2/sweetalert2.d.ts(402,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'preConfirm' must be of type '(inpu
tValue: any) => any', but here has type '(inputValue: any) => Promise'.
src/assets/vendors/bower_components/sweetalert2/sweetalert2.d.ts(481,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'inputValidator' must be of type '(
inputValue: any) => string | Promise', but here has type '(result: any) => Promise'.
src/assets/vendors/bower_components/sweetalert2/sweetalert2.d.ts(493,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'progressSteps' must be of type 'st
ring[]', but here has type 'SweetAlertOptions[]'.
src/assets/vendors/bower_components/sweetalert2/sweetalert2.d.ts(520,5): error TS2300: Duplicate identifier 'default'.

thanks

Installation

I followed the installation guide but didnt work.

When I use:

<button [swal]="['Delete?', 'This cannot be undone.', 'warning']">
  Delete
</button>

I get:

ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'swal' since it isn't a known property of 'button'. 

I did the npm install at repository @toverux/ngsweetalert2 and added at my app.molule the import.
I miss something?

simple swalPartial directive not working

I'm trying to show an alert using the swalPartial directive, but it's empty and it should be showing the label "how are you?" as content, or maybe I'm missing something? (take a look at app/app.component.html)

here's a minimal repo reproducing the issue: https://bitbucket.org/tavuntu/testswal

just run npm i and ng serve

maybe it has something to do with this? (I'm using Angular CLI 1.5.4.)

cancel/dismiss button markup getting set to display: none;

For some reason when using the [swal] attribute in a <button> element, (cancel) generates the button markup for it properly, however for some reason it is set to display: none;.

I have tried placing cancel before confirm like this...

<button [swal]="['Delete?', 'This cannot be undone.', 'warning']" (cancel)="cancelTest()" (confirm)="confirmTest()"> Test Sweet Alert </button>

and I've tried it with cancel after the confirm like this...

<button [swal]="['Delete?', 'This cannot be undone.', 'warning']" (confirm)="confirmTest()" (cancel)="cancelTest()"> Test Sweet Alert </button>

Thanks in advance.

Update:

  • I should note that my confirmTest() is being triggered when the 'ok' button is selected by user.

Did another test or two...

  • I also just tried to create a sweet alert with no confirm method and just a cancel method. When I did this, it created an 'ok' button in the dialog, however it didn't call my (cancel) method, it just fired off into nothingness. I would imagine sweet alert automatically creates an confirm method and 'ok' button no matter what....idk. During this test when I viewed the markup, both the confirm and cancel button markup appeared, however once again the 'cancel' button's button element was set to display: none;

Stop opening of alert in beforeOpen event?

I'm trying to prevent swal from opening if nothing is selected.
Here's how I initialize it.

          <swal
            #deleteSwal
            text="Are you sure you want to delete the following products?"
            type="question"
            [showCancelButton]="true"
            (confirm)="onDelete()"
            (beforeOpen)="beforeOpenDelete()"
          ></swa>

Is it possible to interrupt the opening process in beforeOpen event?

Issue with alert closing

Hi... I'm having trouble using sweetAlert. When it is closed, swal2-container blocks the other components of the screen.

How to use Angular Template Syntax inside alerts

Is it possible to put a list into html?
Something like this:

<ul>
  <li *ngFor="let hero of heroes">
    {{ hero }}
  </li>
</ul>

I need to show list as the text of the swal, this is what I do:

swal({
        title: 'title',
        type: 'error',
        html: '<ul><li *ngFor="let err of messageErr">{{err}}</li></ul>'
      });

But It seems that don't evaluate {{ err }}
cattura

*swalPartial does not override <swal> content

Hi there, how do I replace the content of the popup to use the angular 2 syntax ?
Let's say I have this:

    <swal #PagesPopUp
          type="question"
          showCancelButton = "true"
          (confirm)="Save()"
          confirmButtonText='Save'>
        <form *swalPartial>
        </form>
        <ng-container *swalPartial="swalTargets.title">
            Tile Replace with this ({{ title }})
        </ng-container>
        <ng-container *swalPartial="swalTargets.content">
            <h1> Shoild it replace the content? {{ content }}</h1>
        </ng-container>
    </swal>

As you see, I add
*swalPartial="swalTargets.content" to replace the content. but It doesn't work

Also, how do I call a SwalPartialDirective from the typescript code? right now I use PagesPopUp.show() and I don't know if this is the right way to do it

Thanks,

The order of confirm/cancel is different?

When I test the original SweetAlert, the confirm button is on the right, and the cancel button is on the left.

When I test the ngSweetAlert2, the confirm button is on the left, and cancel is on the right.

Am I missing something, or it was a choice to change the orders?

install using yarn failed

I use jhipster angular 4 generator and add sweetalert angular dependency

yarn add sweetalert2 @toverux/ngx-sweetalert2

And I got this error on running using webpack dev server

Uncaught Error: Unexpected value '[object Object]' imported by the module 'MyModule'. Please add a @NgModule annotation.
    at syntaxError (webpack-internal:///./node_modules/@angular/compiler/@angular/compiler.es5.js:1918)
    at eval (webpack-internal:///./node_modules/@angular/compiler/@angular/compiler.es5.js:15614)
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver.getNgModuleMetadata (webpack-internal:///./node_modules/@angular/compiler/@angular/compiler.es5.js:15597)
    at CompileMetadataResolver.getNgModuleSummary (webpack-internal:///./node_modules/@angular/compiler/@angular/compiler.es5.js:15539)
    at eval (webpack-internal:///./node_modules/@angular/compiler/@angular/compiler.es5.js:15612)
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver.getNgModuleMetadata (webpack-internal:///./node_modules/@angular/compiler/@angular/compiler.es5.js:15597)
    at CompileMetadataResolver.getNgModuleSummary (webpack-internal:///./node_modules/@angular/compiler/@angular/compiler.es5.js:15539)
    at eval (webpack-internal:///./node_modules/@angular/compiler/@angular/compiler.es5.js:15612)

Thanks

package.json version

When I put "ngsweetalert2" into my package.json it tells me unavailable for the version.
If I try to get packages with no version number i get this error:
npm ERR! 404 'ngsweetalert2' is not in the npm registry.

Use from a service

Is it possible to use it from a service? Something like:

sweetAlert.swal({
      title: 'Confirmation',
      text: 'Text.',
      type: 'question',
      showCancelButton: true,
      confirmButtonText: 'Yes',
      cancelButtonText: 'Cancel',
    })

Thank you

[Question] Handling async/await or how to properly create a reusable swal

Sorry in advance if this is a question more suited for Stack Overflow, but there is not a tag for ngx-sweetalert2. I can move this if needed.

I have a swal.service.ts file with the following:

import { Injectable } from '@angular/core';
import swal from 'sweetalert2';

@Injectable()
export class SwalService {
    public showSwal() {
        swal({
            title: 'Are you sure?',
            text: 'You will not be able to recover this imaginary file!',
            type: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'No, keep it'
        }).then((result) => {
            if (result.value) {
                swal(
                    'Deleted!',
                    'Your imaginary file has been deleted.',
                    'success'
                );
                return true; // is there a way I can return what option was chosen back to the component.ts?
            }
            // else if (result.dismiss === swal.DismissReason.cancel) { // DismissReason doesn't exist on swal??
            //     swal(
            //         'Cancelled',
            //         'Your imaginary file is safe :)',
            //         'error'
            //     );
            // }
        });
    }
}

and I call it from my component.ts:

const chosenBoolean = await this.swalService.showSwal();
console.log("chosenBoolean: " + chosenBoolean);

My await syntax is pseudo-code of what I'm trying to accomplish. Is there a way I can use async/await in this manner? Is there a different way to achieve this? My overall goal is to have reusable SweetAlert service that I call from different components and return what option/button the user clicked to the component and take various actions based upon what was selected.

how to use i18n in default options

I use this default options for ngsweetalert2:

imports: [
        SweetAlert2Module.forRoot({
            confirmButtonText: 'Yes',
            cancelButtonText: 'Cancel',
            showCancelButton: true
        })
    ]

But i don't know how to use i18n in this config. I'm using the ngx-translate component .
I mean when the langage is chinese, the confirmButtonText should be "确定",and the cancelButtonText should be "取消". but, i don't know how to change it.

Hope your help!

How to implement preConfirm event in directive

How to implement preConfirm event in directive ? I just found 2 event in documentation, confirm and cancel. Where to place preConfirm event ?

I have tried to add it inside options

[swal]="{preConfirm: preConfirm() }"

but the preConfirm was not found

ERROR TypeError: params.preConfirm is not a function

Type Error

Getting type exception after code running.

[at-loader] Checking finished with 2 errors
[at-loader] node_modules\sweetalert2\sweetalert2.d.ts:212:9
TS1110: Type expected.

[at-loader] node_modules\sweetalert2\sweetalert2.d.ts:308:20
TS1110: Type expected.

Error handling with show().then()

Hi,

I would like to achieve a simple deletion confirmation swal.

So for the moment I have a <swal></swal> as followed :

<swal #dialog title="Delete?" type="warning" (confirm)="onDelete(item)"></swal>
<swal #dialogsuccess title="Deleted!" type="success"></swal>
<swal #dialogerror title="Error!" text="An error has been raised" type="error"></swal>
<button md-button class="action-buttons" mdTooltip="Delete" mdTooltipPosition="right" (click)="dialog.show().then(dialogsuccess.show)"></button>

The onDelete() function returns a Promise but I don't really know how to handle errors in the dialog.show().then right now, even if the Promise returns an error, I can't handle it with a proper swal

I can't really do the same as in VanillaJS

Thanks in advance

Unknown parameter "0" when using options

Hi,

I'm using ngsweetalert2 and I'm a bit struggling.
I would like to create a modal for a request with the preConfirm option (similar to the Ajax request example in the official documentation)

The problem is, when I'm using :

<swal #dialog title="Delete?" type="warning"
   options="{showLoaderOnConfirm=true, preConfirm: onDelete(item.pId) }"></swal>

I am having SweetAlert2: Unknown parameter "0" in my console (and it goes from "0" to "74").
Even when options={} is empty, I'm having the error from "0" to "1"

Thanks in advance for your help


Project INFO:
Angular: 4.2.2

Translation in sweetalert

Is it possible to ha a sweetalert localized?
In my angular application I am using ngx-translate and in my html I have something like this:
{{user.validations.invalid | translate}}

If it's not possible is there a way to have a translation in my sweetalert?

Cancel button triggers confirm

I think this just started happening after a recent update. Seems that the confirm function triggers even when clicking cancel or dismissing the modal. I don't think this was happening a few weeks ago when I first started using ngx-sweetalert2. Here's one example of the code:

<i *ngIf="store.isActive" [swal]="{title: 'Deactivate Store', text: store.storeName, type: 'question', showCancelButton: true}" (confirm)="toggleActive(store, false)" class="fa fa-2x fa-power-off text-success ml-1" placement="top" ngbTooltip="Deactivate"></i>

Opening Sweetalert from Typescript

Hi, all your examples show how to display an alert from the view in html, I was wondering how you would display it from the typescript. For example, displaying a success alert once data has been posted to the server.

How to implement a counter

I am using ng-idle to implement a session timeout counter. What is the best way to update the swal dialog text ? Right now, I am calling show multiple times in the subscribe of count down timer change but that is throwing alert multiple times instead of just updating the time value. It worked earlier today without throwing multiple alerts but I am not sure what I changed but it stopped working correctly.

Replace OpaqueTokens with InjectionTokens to support Angular 5.0

To produce the below. Upgrade the project to Angular 5.0
Can we have this fixed

WARNING in ./node_modules/@toverux/ngsweetalert2/dist/types+es2015-modules/src/di.js
2:31-42 "export 'OpaqueToken' was not found in '@angular/core'
    at HarmonyImportSpecifierDependency._getErrors (/MYPROJECTXXX/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:65:15)
    at HarmonyImportSpecifierDependency.getWarnings (/MYPROJECTXXX/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:39:15)
    at Compilation.reportDependencyErrorsAndWarnings (/MYPROJECTXXX/node_modules/webpack/lib/Compilation.js:703:24)
    at Compilation.finish (/MYPROJECTXXX/node_modules/webpack/lib/Compilation.js:561:9)
    at applyPluginsParallel.err (/MYPROJECTXXX/node_modules/webpack/lib/Compiler.js:506:17)
    at /MYPROJECTXXX/node_modules/tapable/lib/Tapable.js:289:11
    at _addModuleChain (/MYPROJECTXXX/node_modules/webpack/lib/Compilation.js:507:11)
    at processModuleDependencies.err (/MYPROJECTXXX/node_modules/webpack/lib/Compilation.js:477:14)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
 @ ./node_modules/@toverux/ngsweetalert2/dist/types+es2015-modules/src/di.js
 @ ./node_modules/@toverux/ngsweetalert2/dist/types+es2015-modules/index.js
 @ ./src/app/app.module.ts
 @ ./src/main.ts
 @ multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts

Duplicate identifier

I'm using with angular4 and when i try to add the module to the project the angular cli give me the duplicate error (below). I added the css file, to the angular-cli config file, imported the module to the project and when i need to use in typescript i import the sweetalert2 directly.

Looks like this error is caused by my manual import of sweetalert2 and the module. But that's the recommendation. What can i do in this case ?

the error:

ERROR in ...../node_modules/sweetalert2/sweetalert2.d.ts (203,17): Duplicate identifier 'SweetAlertType'.
ERROR in ...../node_modules/sweetalert2/sweetalert2.d.ts (205,17): Duplicate identifier 'SweetAlertInputType'.
ERROR in ...../node_modules/sweetalert2/sweetalert2.d.ts (207,17): Duplicate identifier 'SweetAlertInputOptions'.
ERROR in ...../node_modules/sweetalert2/sweetalert2.d.ts (209,17): Duplicate identifier 'SweetAlertInputAttributes'.
ERROR in ...../node_modules/sweetalert2/sweetalert2.d.ts (614,5): Duplicate identifier 'default'.
ERROR in ...../node_modules/@toverux/ngsweetalert2/node_modules/sweetalert2/sweetalert2.d.ts (203,17): Duplicate identifier 'SweetAlertType'.
ERROR in ...../node_modules/@toverux/ngsweetalert2/node_modules/sweetalert2/sweetalert2.d.ts (205,17): Duplicate identifier 'SweetAlertInputType'.
ERROR in ...../node_modules/@toverux/ngsweetalert2/node_modules/sweetalert2/sweetalert2.d.ts (207,17): Duplicate identifier 'SweetAlertInputOptions'.
ERROR in ...../node_modules/@toverux/ngsweetalert2/node_modules/sweetalert2/sweetalert2.d.ts (209,17): Duplicate identifier 'SweetAlertInputAttributes'.
ERROR in ...../node_modules/@toverux/ngsweetalert2/node_modules/sweetalert2/sweetalert2.d.ts (614,5): Duplicate identifier 'default'.

my root module:

import {SweetAlert2Module} from '@toverux/ngsweetalert2';

imports: [
   SweetAlert2Module.forRoot()
]

my ts file:

import {TranslateService} from 'ng2-translate';

constructor() {
   swal('foo');
  }

EDIT: Format

404 importing SweetAlert2Module

Hi @toverux,

I'm trying to integrate ngx-sweetalert2 with my angular 5 app but I'm receiving a 404 whe importing the:

import { SweetAlert2Module } from '@toverux/ngx-sweetalert2';

using (confirm) inside ngFor ?

am using the confim alert as below

<li class="list-group-item row mb-0" *ngFor="let l of myarray">
    <div class="col-md-5">{{l.a}}</div>
    <div class="col-md-5">{{l.b}}</div>
    <div class="col-md-2">
        <i class="fa fa-trash fa-lg" [swal]="delete" (confirm)="delete(l)"></i>
    </div>
</li>

<swal #delete title="Are you sure you want to delete?" text="This cannot be undone" type="question"  [showCancelButton]="true" [focusCancel]="true"></swal>

and the delete() method remove the selected element from the array .. but when i use this code .. the (confirm) runs on all array elements and delete them one by one !!? its like the confirm called more than once !!?

Is it possible to use other components inside sweetalert?

Is it possible to put some third part component inside sweetalert?
I want to show my sweetalert when someone have to change password, Inside this sweetalert I need 3 input fields ( old password, new password and confirm new password)
But the new password field needs to be a something like this:
https://www.primefaces.org/primeng/#/password or
https://github.com/rnadler/ng2-password-strength-bar
Is it possible to use different input fields?

Error when opening/closing quickly

Thanks for this great package!
Works like a charm :)

To reproduce the bug :
Paste this in the template:
<button [swal]="['1', '2', 'warning']">
Delete

On the browser, focus on the button and press enter 6 times quickly. This message will show in the console.

core.es5.js:1084 ERROR TypeError: Cannot read property 'removeChild' of null
at removeModalAndResetState (sweetalert2.js:1518)
at HTMLDivElement.swalCloseEventFinished (sweetalert2.js:1530)
at ZoneDelegate.invokeTask (zone.js:398)
at Object.onInvokeTask (core.es5.js:4116)
at ZoneDelegate.invokeTask (zone.js:397)
at Zone.runTask (zone.js:165)
at HTMLDivElement.ZoneTask.invoke (zone.js:460)

Is there a way to use a variable instead of a string message?

Hi, I'm trying to use a variable instead of string, is there a way to do that?
in the following example deleteMsg it's a public string variable.

<button class="btn" [swal]="{text: deleteMsg, showCancelButton: true, confirmButtonText: 'Yes', cancelButtonText: 'Cancel'}" (confirm)="delete(user)">

Thanks

The right way to use it in Angular 2+

Hello, is this the right way to use?

<swal #foo title="Confirma liquidação?"
    [options]="{
        confirmButtonText: 'Liquidar',
        confirmButtonClass: 'btn btn-xs btn-success',
        cancelButtonClass: 'btn btn-xs btn-danger',
        cancelButtonText: 'Cancelar',
        showCancelButton: true
    }"
    (confirm)="confirmar()"
    (cancel)="cancelar()">
</swal>
<button type="button"
    (click)="foo.show()"
    class="btn btn-xs btn-success">
    Liquidar
</button>

Also I would need to change the directive name to something like and [d-swal] because of the name patterns we use, is there a way to do it?

100 ★

Congratulations with the first remarkable milestone 🎉 🎉 🎉

Many thanks @toverux for making the Angular community a bit better. Hopefully, in the near future, we will be able to provide integrations for Vue and React as good as this one.

Have a nice Sunday!

troubles with imports or installation(angular 2.4.1)

i did this:

npm install --save sweetalert2 @toverux/ngx-sweetalert2

and this in my app.module:

import { SweetAlert2Module } from '@toverux/ngx-sweetalert2';
imports: [
   ...........
    SweetAlert2Module.forRoot()
  ],

and i had this:
image

i can not use route.navigate after then

I want to move the component after the OK button is pressed.
I use code like this,

result.subscribe((data) => { swal({ title: 'Good job!', text: data.message, type: 'success', }).then(function () { this.router.navigate(['menus/categories']); }); });

But the result of a console like this,

RROR Error: Uncaught (in promise): TypeError: Cannot read property 'router' of undefined TypeError: Cannot read property 'router' of undefined at form.component.ts:94

Is there anything wrong or can not be with route.navigate?

Use directly from component or service?

Hi,

I'm asking myself the question if it's possible to show the dialog directly from a component? Meaning I don't have a visual action that will trigger the show functionality.

For the moment I have to call another service and when this service resolves I will show an alert saying it's okay.

Tried to call functions directly from my component, but it doesn't work because of type issue and can't figure how exactly:

import * as swal from 'sweetalert2';

this.myService().subscribe((res) => {
      swal('Keep things simple :)');
      swal('The Internet?', 'That thing is still around?', 'question');
    });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.