繁体   English   中英

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

[英]Angular - Is it possible to prevent executing a (click) event by a directive?

我创建了以下指令,我想阻止(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() {
  }
}

这是我的标记:

<button (click)="shouldNotBeExecuted()" disabledButton>Push Me</button>

在上面相同的情况下,我希望不执行shouldNotBeExecuted()方法。 但它是...

是的,这是可能的:

@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();
  }
}

Ng 运行示例

我认为,当前代码没有问题
preventDefault - 只是阻止默认操作,例如对于链接,它将引导您到另一条路线等等
stopPropagation - 防止通过 DOM 树进行传播

解决此问题的一些方法是将按钮设置为禁用或检查,该事件被阻止默认:

<button (click)="shouldNotBeExecuted($event)" disabledButton>Push Me</button>

@Component({
  selector: "app",
  templateUrl: "./app.component.html"
})
export class AppComponent  {
  shouldNotBeExecuted(event: MouseEvent): void {
    if(event.defaultPrevented ) {
      console.log('prevented');
    }
  }
}

您可以使用“禁用”属性来防止点击

<button (click)="shouldNotBeExecuted()" [disabled]="your condition here">Push Me</button>

如果您将按钮设为组件,则可以为回调使用不同的属性,以便控制何时调用它。

<fancy-button (onPress)="shouldNotBeExecuted()">
    Press Me
</fancy-button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM