html - 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
事件。是否有任何解决方案我不必在其调用中控制操作本身?
解决方案
防止禁用按钮上的点击事件
如果该disabled
属性存在,则不会发生单击。
当用户决定使用 devtools
但是,如果用户编辑 HTML 并手动删除 disabled 属性,则会发生单击。您可以尝试按照您的建议进行检查,但浏览器是一个不安全的环境。无论您可能进行任何前端检查,用户仍然可以代表网页上执行任何代码。
推荐阅读
- ios - iOS App Rejected EXC_BAD_ACCESS (SIGSEGV) - 无法重现错误
- python - TypeError: 'int' 对象不可调用 total_interest = num_payments(years * 12) * loanpayment(principal, percent, years)
- entity-relationship - 双方一对一关系的实体关系
- javascript - 如何使用 Formik Yup 验证多个电话号码
- c++ - 如何通过保存在容器中的成员指针函数调用?
- sparql - 使用 SPARQL 查询时,如何保护运行 Sesame Triplestore 的系统免受注入?
- python - 如何将变量分配给 matplotlib 图形对象并在布局中重用它
- reactjs - React Hook useEffect 缺少依赖项:'execute'
- javascript - Google Apps 脚本:将 Gmail 附件保存到 Google Drive
- python - HTTP GET API 设计,它使用相同的端点,但在 Flask 中提供带有请求参数的过滤结果