Declarative, template-driven SweetAlert2 integration for Angular 4+
Clone or download

README.md

SweetAlert2

ngx-sweetalert2

Official SweetAlert2 integration for Angular 4+

npm version license npm total downloads npm legacy total downloads


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.

πŸ‘‰ Migrating from v2.x to v3.x? Read the release notes!

πŸ‘‰ Before posting an issue, please check that the problem isn't on SweetAlert's side.



πŸ“¦ Installation & Usage

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

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

  1. Import the module:
import { SweetAlert2Module } from '@toverux/ngx-sweetalert2';

@NgModule({
    //=> Basic usage
    imports: [SweetAlert2Module.forRoot()],

    //=> Or provide default SweetAlert2-native options
    //   (here, we make Swal more Bootstrap-friendly)
    imports: [
        SweetAlert2Module.forRoot({
            buttonsStyling: false,
            customClass: 'modal-content',
            confirmButtonClass: 'btn btn-primary',
            cancelButtonClass: 'btn'
        })
    ],

    //=> In submodules only:
    imports: [SweetAlert2Module]
})
export class AppModule {
}

πŸ”— 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 (, type: string)].

Simple dialog:

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

More advanced (input in dialog, dismissal handling):

<button
  [swal]="{ title: 'Enter your email', input: 'email' }"
  (confirm)="saveEmail($event)"
  (cancel)="handleRefusalToSetEmail($event)">

  Set my e-mail address
</button>
export class MyComponent {
  public saveEmail(email: string): void {
    // ... save user email
  }

  public handleRefusalToSetEmail(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 ...></swal>

SwalComponent

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

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

Simple example:

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

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

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

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

class MyComponent {
  @ViewChild('deleteSwal') private deleteSwal: SwalComponent;
}

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

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

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

<swal (beforeOpen)="onBeforeOpen($event)" (open)="onOpen($event)" (close)="onClose($event)"></swal>
public onBeforeOpen(event: BeforeOpenEvent): void {
  // You can access the modal's native DOM node:
  console.log(event.modalElement);
}

SwalPartialDirective

So you really want more, huh?

The *swalPartial directive lets you use Angular dynamic templates inside SweetAlerts. The directive will replace certain parts of the modal (aka. swal targets) with embedded Angular views.

This allows you to have data binding, use directives and components and benefit from the Angular template syntax like if the SweetAlert was a normal Angular component (it's not. at all).

<swal title="SweetAlert2 Timer">
  <div *swalPartial class="alert alert-info">
    <strong>{{ elapsedSeconds }}</strong> seconds elapsed since then.
  </div>
</swal>

The other cool thing about using a structural directive is that the modal's contents won't be instantiated before the modal is shown.

But, I want to use a template inside the modal's title. Your example only sets the main content.

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

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

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

And then, set the appropriate target as the value of *swalPartial.

<swal title="Fill the form, rapidly">
  <!-- This form will be displayed as the alert main content
       Targets the alert's main content zone by default -->
  <form *swalPartial [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 *swalPartial="swalTargets.confirmButton">
    Send ({{ secondsLeft }} seconds left)
  </ng-container>
</swal>

We have the following targets: title, content, actions, confirmButton, cancelButton. These are provided by SweetAlert2.