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

时间:2020-08-14 16:23:20

标签: 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() {
  }
}

这是我的标记:

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

在上述相同的内容中,我希望不执行shouldNotBeExecuted()方法。但这是...

4 个答案:

答案 0 :(得分:2)

是的,有可能:

@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

答案 1 :(得分:0)

我认为,当前代码没有问题
preventDefault-仅阻止默认操作,例如进行链接,它会将您定向到另一条路线,依此类推
stopPropagation-防止通过DOM树传播

一些解决此问题的方法是将按钮设置为禁用或选中,以防止该事件发生。Default:

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

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