To execute an asynchronous call and maintain the alert open, you must define the preConfirm
property along with showLoaderOnConfirm
. Instead of listing all the SweetAlert configuration options in the HTML, it is recommended to create a property of type SweetAlertOptions
within the component class and then utilize property binding with the [options]
@Input decorator provided by the <swal></swal>
component.
For this purpose, import SweetAlertOptions
as follows:
import swal, { SweetAlertOptions } from 'sweetalert2';
A button has been implemented in the component class to trigger the alert manually, and .then()
is used to display the success message upon completion of the asynchronous operation. The utilization of ViewChild
and the imported SwalComponent
have facilitated this process.
Snippet for the component class
app.component.ts
import { Component, ViewChild} from '@angular/core';
import swal,{ SweetAlertOptions } from 'sweetalert2';
import { SwalComponent } from '@toverux/ngx-sweetalert2';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 4';
public alertOption:SweetAlertOptions = {};
@ViewChild('saveSwal') private saveSwal: SwalComponent;
constructor(){
this.alertOption = {
title:"Are you sure?",
text:"Do you want to save changes",
cancelButtonColor:"#d33",
showCancelButton:true,
cancelButtonText:"No! Review",
confirmButtonColor:"#3085d6",
confirmButtonText:'Yes, Save progress',
showLoaderOnConfirm:true,
focusCancel:true,
preConfirm: () => {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Doing async operation");
resolve()
}, 5000)
})
},
allowOutsideClick: () => !swal.isLoading()
}
}
showAlert(evt:any){
this.saveSwal.show().then(() => {
swal({
type: 'success',
title: 'Ajax request finished!'
})
})
}
save(){
console.log("data saved");
}
}
HTML file
app.component.html
<swal #saveSwal
(confirm)="save()"
[options]="alertOption"
>
</swal>
<button (click)="showAlert($event)">Click here</button>
Module file
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { SweetAlert2Module } from '@toverux/ngx-sweetalert2';
@NgModule({
imports: [ BrowserModule, FormsModule, SweetAlert2Module.forRoot()],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
This setup ensures that the loader remains visible during the async call, displaying the success message only after its completion.
Check out the live demo:
https://stackblitz.com/edit/angular4-ifaa17?file=app%2Fapp.component.ts