Angular Delete Confirmation Directive

Create Angular project from scratch with Webpack

Every sensitive operation needs to ask for confirmation or provide an option to undo.

We can create a custom directive that can be reused everywhere.

First will generate an empty directive, Let’s name it delete-confirmation

ng g d delete-confirmation

Now will add host listener for click event, and ask for confirmation.

Here I used the browser native confirm function for demo purposes. Of course, you can create your own dialog or use material/bootstrap dialog.

@HostListener("click")
confirmDelete()  {
	const confirmation = confirm("Are you sure ?");
	if  (conf)  {
		this.deleteIt.emit();
	}
}

A popup will be displayed asking for Are you sure when the user clicks on the directive’s element.

When canceled will do nothing, but upon clicking on yes will emit an output event

@Output() deleteIt =  new  EventEmitter<MouseEvent>();

The Consumer of the directive can listen to the deleteIt event and perform further action

<button (deleteIt)="proceedToDelete()">Delete<button>

That’s it!


Additionally, we can add @Input deleteMsg to display a custom delete message

@Input() deleteMsg = 'Are you sure?';
...
const confirmation = confirm(this.deleteMsg);
<button (deleteIt)="proceedToDelete()" deleteMsg="Do you want to proceed?">Delete<button>

Other points
We cannot use click event to output a confirmation event, It would lead to a maximum call stack size exceeded error because of the recursive call.

Stackblitz example

Comments