UPDATE: Plunkr added
I was looking for a solution on all forums but found none, so found a solution with Old School Javascript Callback function.
This is a really simple and clean way to create a confirmation dialog and set Callback functions for both YES and NO click events.
I have used Bootstrap CSS for Modal and An Alert Service with rxjs Subject.
alert.component.html
<div *ngIf="message.type == 'confirm'" class="modal-body">
<div class="row">
<div class="col-md-12">
<h3 class="text-center">{{message.text}}</h3>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-center">
<a (click)="message.noFn()">
<button class="btn btn-pm">No</button>
</a>
<a (click)="message.siFn()">
<button class="btn btn-sc" >Yes</button>
</a>
</p>
</div>
</div>
</div>
alert.component.ts
export class AlertComponent {
message: any;
constructor(
public router: Router,
private route: ActivatedRoute,
private alertService: AlertService,
) { }
ngOnInit() {
//this function waits for a message from alert service, it gets
//triggered when we call this from any other component
this.alertService.getMessage().subscribe(message => {
this.message = message;
});
}
The most important part is here alert.service.ts
import { Injectable } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
@Injectable() export class AlertService {
private subject = new Subject<any>();
constructor(){}
confirm(message: string,siFn:()=>void,noFn:()=>void){
this.setConfirmation(message,siFn,noFn);
}
setConfirmation(message: string,siFn:()=>void,noFn:()=>void) {
let that = this;
this.subject.next({ type: "confirm",
text: message,
siFn:
function(){
that.subject.next(); //this will close the modal
siFn();
},
noFn:function(){
that.subject.next();
noFn();
}
});
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
Call the function from any component
this.alertService.confirm("You sure Bro?",function(){
//ACTION: Do this If user says YES
},function(){
//ACTION: Do this if user says NO
})