Angular - Prevent click event on disabled buttons

Discussão em 'Angular' iniciado por dev_054, Dezembro 8, 2024.

  1. dev_054

    dev_054 Guest

    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.

    For now, I have the following code to do this:

    <button [disabled]="someCondition" (click)="executeAction()">Execute action</button>


    executeAction(): void {
    if (this.someCondition) return;

    // ...
    }


    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 Linter can't help me here).

    Looking for a more robust solution, I thought that directive could help me:

    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
    }
    }
    }


    <button [disabled]="someCondition" (click)="executeAction()">Execute action</button>


    executeAction(): void {
    console.log('still being called');
    }


    ...however it does absolutely nothing. It doesn't prevent the click event. Is there any solution that I don't have to control the action itself in its call?

    STACKBLITZ

    Continue reading...

Compartilhe esta Página