Angular - 是否可以通过指令阻止执行(单击)事件?

ada*_*ily 2 javascript angular

我创建了以下指令,我想阻止该(click)事件在某些条件下执行(或延迟点击,或要求用户确认等)。出于演示目的,我的以下目标只是完全阻止执行该事件:

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[disabledButton]'
})
export class DisabledButtonDirective {

  @HostListener('click', ['$event'])
  clickEvent(event) {
    event.stopImmediatePropagation();
    event.preventDefault();
    event.stopPropagation();
  }

  constructor() {
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我的标记:

<button (click)="shouldNotBeExecuted()" disabledButton>Push Me</button>
Run Code Online (Sandbox Code Playgroud)

在上面的内容中,我希望该shouldNotBeExecuted()方法不被执行。但它是...

yur*_*zui 6

是的,这是可能的:

@Directive({
  selector: '[disabledButton]'
})
export class DisabledButtonDirective {
  subscription = new Subscription();

  constructor(private elRef: ElementRef) {}

  ngOnInit() {
    const el = this.elRef.nativeElement;
    this.subscription = fromEvent(el.parentNode, 'click', { capture: true })
      .subscribe((e: any) => {
        if (e.target === el) {
          e.stopPropagation()
        }
      }); 
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}
Run Code Online (Sandbox Code Playgroud)

NG 运行示例