首页 > 解决方案 > Angular - 防止禁用按钮上的点击事件

问题描述

我试图阻止禁用按钮上的单击事件,换句话说,阻止某些删除禁用属性的用户调用某些操作。

现在,我有以下代码来执行此操作:

<button [disabled]="someCondition" (click)="executeAction()">Execute action</button>
executeAction(): void {
  if (this.someCondition) return;

  // ...
}

有效,但这不是一个好的解决方案,因为我必须为我的应用程序中的所有按钮都这样做(相信我,很容易忘记这样做,甚至Linter也无法帮助我)。

寻找更强大的解决方案,我认为这directive可以帮助我:

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');
}

...但是它完全没有任何作用。它不会阻止click事件。是否有任何解决方案我不必在其调用中控制操作本身?

堆栈闪电战

标签: htmlangulartypescriptdom-events

解决方案


防止禁用按钮上的点击事件

如果该disabled属性存在,则不会发生单击。

当用户决定使用 devtools

但是,如果用户编辑 HTML 并手动删除 disabled 属性,则会发生单击。您可以尝试按照您的建议进行检查,但浏览器是一个不安全的环境。无论您可能进行任何前端检查,用户仍然可以代表网页上执行任何代码。


推荐阅读