Home > Software engineering >  Angular directive to stop default click event
Angular directive to stop default click event

Time:11-26

The use case is, using Angular, create a directive that can be used to stop the default (click) event if a condition is true. If false, allow that default (click) event to fire.

All the code below works, except it does NOT stop propagation, so the click event handler on the button is still firing.

HTML

        <button mat-raised-button color="primary" [myDisabled]="reactiveForm.invalid" (click)="onSubmit()">A11y Disabled</button>

Typescript directive

import { Directive, ElementRef, HostListener, Input, Renderer2, TemplateRef, ViewContainerRef } from "@angular/core";

@Directive({
  selector: '[myDisabled]',
})
export class A11yDisabled {

private _isdisabled: boolean = false

constructor(
    private _elementRef: ElementRef,
    private _renderer: Renderer2
){}

@Input() set edjDisabled(condition: boolean) {
    console.log('condition', condition);
    if (condition) {
        this._isdisabled = true;
        this._renderer.addClass(this._elementRef.nativeElement, 'a11y-disabled');
        this._renderer.setAttribute(this._elementRef.nativeElement, 'aria-disabled', 'true');
    } else {
        this._isdisabled = false;
        this._renderer.removeClass(this._elementRef.nativeElement, 'a11y-disabled');
        this._renderer.removeAttribute(this._elementRef.nativeElement, 'aria-disabled');
    }
}


@HostListener('click', ['$event'])
onClick(e: any) {
    console.log('mouseup', this._isdisabled);
    if (this._isdisabled) {
        e.stopPropagation();
        e.preventDefault();
        console.log('stop', this._isdisabled);
    }
}

}

CodePudding user response:

Instead of using click event preventDefault you can use css pointer-event:none to disable all click

import {
  Directive,
  ElementRef,
  Input,
  Renderer2,
  TemplateRef,
  ViewContainerRef,
} from '@angular/core';

@Directive({
  selector: '[myDisabled]'
})
export class A11yDisabled {
  private _isdisabled: boolean = false;
  @Input() set edjDisabled(condition: boolean) {
    console.log('condition', condition);
    if (condition) {
      this._isdisabled = true;
      this._renderer.addClass(this._elementRef.nativeElement, 'a11y-disabled');
      this._renderer.setAttribute(
        this._elementRef.nativeElement,
        'aria-disabled',
        'true'
      );
    } else {
      this._isdisabled = false;
      this._renderer.removeClass(
        this._elementRef.nativeElement,
        'a11y-disabled'
      );
      this._renderer.removeAttribute(
        this._elementRef.nativeElement,
        'aria-disabled'
      );
    }
  }
  @HostBinding('style.pointerEvents') get pE() {
    return this._isdisabled ? 'none' : '';
  }

  @HostBinding('tabindex') get tabIndex() {
    return this._isdisabled ? '-1' : '';
  }

  constructor(private _elementRef: ElementRef, private _renderer: Renderer2) {}
}

Working Example

  • Related