I use angular11 to write my project
in many cases I want a button to have a confirm dialog, so instead of creating a mat-dialog
popup for it, I want to create a directive that when added to the button element, it will show a popup with a custom message with yes/no buttons, and only if the user clicks yes it will perform the actual click event.
so for now I'm just trying to disable the click event, to see if the system works.. and it doesn't :) the click even is still executed.
this is my directive:
import {Directive, ElementRef} from '@angular/core';
@Directive({
selector: '[comTuxinConfirm]'
})
export class TuxConfirmDirective {
constructor(el: ElementRef) {
el.nativeElement.addEventListener('click', this.clickEventHandler);
}
clickEventHandler(e: MouseEvent): boolean {
e.preventDefault();
e.stopPropagation();
return false;
}
}
and this is how I use it:
<button *ngIf="actionLabel" comTuxinConfirm mat-button (click)="onActionClicked()">{{actionLabel}}</button>
when I debug, I see that my event handler for comTuxinConfirm
is executed first, before the onActionClicked()
but still, it continue to execute the actual action.
there is some sort of race condition here cause if I create breakpoints and both locations, then it does stop. so I guess this is not the proper way to do so.
any ideas how to implement this properly ?
thanks
Does it have to be a click event? If it has to be you could try to prevent it with the mousedown event which is fired before the click. But if you want to implement this properly you should probably use an observable.
Your button would look something like this:
<button comTuxinConfirm mat-button (onOk)="onActionClicked()">{{actionLabel}}</button>
And your directive:
export class TuxConfirmDirectiveDirective {
@Output() onOk = new Subject<void>();
constructor(private dialog: MatDialog) {}
@HostListener("click")
click(e: MouseEvent): void {
this.dialog.open(MyDialogComponent).afterClosed().subscribe(r => this.onOk.next());
}
}