簡體   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