简体   繁体   English

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

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

I created the following directive and I'd like to prevent the (click) event from being executed under certain conditions (or delay the click, or ask the user for confirmation, etc).我创建了以下指令,我想阻止(click)事件在某些条件下执行(或延迟单击,或要求用户确认等)。 For demonstrational purposes my goal below is just prevent executing the event at all:出于演示目的,我下面的目标只是完全阻止执行该事件:

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

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

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

  constructor() {
  }
}

This is my markup:这是我的标记:

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

In the same above I'd like the shouldNotBeExecuted() method not to be executed.在上面相同的情况下,我希望不执行shouldNotBeExecuted()方法。 But it is...但它是...

Yes, that's possible:是的,这是可能的:

@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-run Example Ng 运行示例

I think, there is no problem with current code我认为,当前代码没有问题
preventDefault - just prevent default action, eg for link it will direct you to another route and so on preventDefault - 只是阻止默认操作,例如对于链接,它将引导您到另一条路线等等
stopPropagation - prevent propagation through DOM tree stopPropagation - 防止通过 DOM 树进行传播

Some of the ways to solve this problem are set button to disabled or check, that event was preventDefaulted:解决此问题的一些方法是将按钮设置为禁用或检查,该事件被阻止默认:

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

You can make use of the 'disabled' attribute to prevent click您可以使用“禁用”属性来防止点击

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

If you make your button a component, you can use a different attribute for your callback so you can control when it's called.如果您将按钮设为组件,则可以为回调使用不同的属性,以便控制何时调用它。

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

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

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