Skip to content
Advertisement

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). 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. But it is…

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement