【发布时间】:2020-02-20 02:00:31
【问题描述】:
我试图阻止禁用按钮上的点击事件,换句话说,阻止某些删除禁用属性的用户调用某些操作。
目前,我有以下代码来执行此操作:
<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 事件。是否有任何解决方案我不必在其调用中控制操作本身?
【问题讨论】:
-
dev_054 我的回答有帮助吗?
标签: html angular typescript dom-events