您还需要设置
preConfirm
属性以及
showLoaderOnConfirm
,以执行异步调用并保持警报打开状态。不要在HTML中提及sweetalert的所有配置选项,最好创建一个类型为
SweetAlertOptions
的组件类属性,然后使用与
<swal></swal>
组件提供的
[options]
@Input装饰器的属性绑定。
为此,您必须像下面这样导入
SweetAlertOptions
import swal,{ SweetAlertOptions } from 'sweetalert2';
我还创建了一个按钮来手动打开警报,并使用
.then()
在异步操作完成后显示成功消息。我已经使用
ViewChild
并导入
SwalComponent
来实现这一点。
组件类的代码如下:
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>
app.module.ts
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 { }
使用此代码,警报会保持打开状态并显示加载程序,直到异步调用完成,然后才会显示成功消息。
工作演示:
https://stackblitz.com/edit/angular4-ifaa17?file=app%2Fapp.component.ts