Angular 将确认对话框作为添加的属性指令添加到按钮

Angular 将确认对话框作为添加的属性指令添加到按钮,angular,typescript,event-propagation,Angular,Typescript,Event Propagation,我用angular11写我的项目 在许多情况下,我希望一个按钮有一个确认对话框,因此,我不想为它创建一个mat对话框弹出窗口,而是想创建一个指令,当添加到按钮元素时,它将显示一个带有是/否按钮的自定义消息的弹出窗口,并且只有当用户单击是时,它才会执行实际的单击事件 所以现在我只是想禁用click事件,看看系统是否正常工作。。但事实并非如此:)点击偶数仍在执行 这是我的指示: import {Directive, ElementRef} from '@angular/core'; @Direct

我用angular11写我的项目

在许多情况下,我希望一个按钮有一个确认对话框,因此,我不想为它创建一个
mat对话框
弹出窗口,而是想创建一个指令,当添加到按钮元素时,它将显示一个带有是/否按钮的自定义消息的弹出窗口,并且只有当用户单击是时,它才会执行实际的单击事件

所以现在我只是想禁用click事件,看看系统是否正常工作。。但事实并非如此:)点击偶数仍在执行

这是我的指示:

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;
  }

}
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());
  }
}
我就是这样使用它的:

    <button *ngIf="actionLabel" comTuxinConfirm mat-button (click)="onActionClicked()">{{actionLabel}}</button>
{{actionLabel}
调试时,我看到
comTuxinConfirm
的事件处理程序在
onActionClicked()
之前首先执行,但它仍然继续执行实际操作

这里有某种竞争条件,因为如果我创建断点和两个位置,那么它确实会停止。所以我想这不是正确的方法

如何正确实施这一点有什么想法吗


谢谢

它必须是点击事件吗?如果必须这样做,您可以尝试使用在单击之前触发的mousedown事件来阻止它。但是如果你想正确地实现这一点,你可能应该使用一个可观察的

您的按钮将如下所示:

    <button comTuxinConfirm mat-button (onOk)="onActionClicked()">{{actionLabel}}</button>
{{actionLabel}
以及你的指示:

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;
  }

}
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());
  }
}
导出类TuxConfigDirective指令{
@Output()onOk=新主题();
构造函数(私有对话框:MatDialog){}
@HostListener(“单击”)
单击(e:MouseeEvent):无效{
this.dialog.open(MyDialogComponent.afterClosed().subscribe(r=>this.onOk.next());
}
}

真棒的答案。它不必是点击事件。这更有意义。谢谢