title: Angular - Prevent click event on disabled buttons
body: <p>I'm trying to prevent click event on disabled buttons, in other words, prevent some user who removes the disabled attribute to call some action.</p>
  
  <p>For now, I have the following code to do this:</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;button [disabled]="someCondition" (click)="executeAction()"&gt;Execute action&lt;/button&gt;
  </code></pre>
  
  <pre><code>executeAction(): void {
    if (this.someCondition) return;
  
    // ...
  }
  </code></pre>
  
  <p>Works, but it isn't a good solution as I have to do it for ALL buttons in my app (and believe me, it's easy to forgot to do this and even a <em>Linter</em> can't help me here).</p>
  
  <p>Looking for a more robust solution, I thought that <code>directive</code> could help me:</p>
  
  <pre><code>import { Directive, HostListener, Input, Renderer2, ElementRef } from '@angular/core';
  
  @Directive({
    selector: 'button'
  })
  export class ButtonDirective {
    @Input() set disabled(value: boolean) {
      this._disabled = value != null;
      this.renderer2.setAttribute(this.elementRef.nativeElement, 'disabled', `${this._disabled}`);
    }
  
    private _disabled: boolean;
  
    constructor(
      private readonly elementRef: ElementRef,
      private readonly renderer2: Renderer2
    ) { }
  
    @HostListener('click', ['$event'])
    onClick(mouseEvent: MouseEvent) {
      // nothing here does what I'm expecting
      if (this._disabled) {
        mouseEvent.preventDefault();
        mouseEvent.stopImmediatePropagation();
        mouseEvent.stopPropagation();
  
        return false; // just for test
      }
    }
  }
  </code></pre>
  
  <pre class="lang-html prettyprint-override"><code>&lt;button [disabled]="someCondition" (click)="executeAction()"&gt;Execute action&lt;/button&gt;
  </code></pre>
  
  <pre><code>executeAction(): void {
    console.log('still being called');
  }
  </code></pre>
  
  <p>...however it does absolutely nothing. It doesn't prevent the <code>click</code> event. Is there any solution that I don't have to control the action itself in its call?</p>
  
  <p><a href="https://stackblitz.com/edit/angular-xhyu2b" rel="nofollow noreferrer"><strong><em>STACKBLITZ</em></strong></a></p>