Here's a slghtly different take using javascript's native confirm functionality and a custom Angular directive. It's super flexible and pretty lightweight:
Usage:
<button (hrsAreYouSure) (then)="confirm(arg1)" (else)="cancel(arg2)">
This will execute confirm if user presses Ok on the confirmation dialog, or cancel if they
hit Cancel
</button>
Directive:
import {Directive, ElementRef, EventEmitter, Inject, OnInit, Output} from '@angular/core';
@Directive({
selector: '[hrsAreYouSure]'
})
export class AreYouSureDirective implements OnInit {
@Output() then = new EventEmitter<boolean>();
@Output() else = new EventEmitter<boolean>();
constructor(@Inject(ElementRef) private element: ElementRef) { }
ngOnInit(): void {
const directive = this;
this.element.nativeElement.onclick = function() {
const result = confirm('Are you sure?');
if (result) {
directive.then.emit(true);
} else {
directive.else.emit(true);
}
};
}
}