Skip to content

Setting global defaults (SweetAlert2 mixins)

Morgan Touverey Quilling edited this page Dec 28, 2020 · 1 revision

Setting global default options for your modals is no longer directly supported by this library, because SweetAlert2 now has a way to do that natively with mixins, so we'll use that!

ngx-sweetalert2 provides a way to provide a custom implementation of SweetAlert2 at module level. We can override the default to replace it with your own mixin, effectively providing default values.

This is how we do it:

@NgModule({
  imports: [
    SweetAlert2Module.forRoot({
      provideSwal: () => import('sweetalert2').then(({ default: swal }) => swal.mixin({
        // example: set global options here
        confirmButtonText: `Confirmer`,
        cancelButtonText: `Annuler`
      }))
    })
  ]
})
export class AppModule {
}

(Please note that this can be overriden again in child modules with .forChild).

The library's default value for provideSwal is simply () => import('sweetalert2').

Instead, here we're retrieving the library instance in the default export, and then we call swal.mixin() on it, which will return a compatible API that ngx-sweetalert2 will be able to use, but parametrized with your default values.

Please note, by the way, that this allows you to completely replace the way SweetAlert2 is loaded and/or tamper with the implementation ngx-sweetalert2 will have access to.