我创建了以下指令,我想阻止 (click)
事件在特定条件下执行(或延迟点击,或要求用户确认等)。出于演示目的,我的以下目标只是完全阻止执行事件:
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[disabledButton]'
})
export class DisabledButtonDirective {
@HostListener('click', ['$event'])
clickEvent(event) {
event.stopImmediatePropagation();
event.preventDefault();
event.stopPropagation();
}
constructor() {
}
}
这是我的标记:
<button (click)="shouldNotBeExecuted()" disabledButton>Push Me</button>
在上面我希望 shouldNotBeExecuted()
方法不被执行。但这是...
最佳答案
是的,这是可能的:
@Directive({
selector: '[disabledButton]'
})
export class DisabledButtonDirective {
subscription = new Subscription();
constructor(private elRef: ElementRef) {}
ngOnInit() {
const el = this.elRef.nativeElement;
this.subscription = fromEvent(el.parentNode, 'click', { capture: true })
.subscribe((e: any) => {
if (e.target === el) {
e.stopPropagation()
}
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
关于javascript - Angular - 是否可以通过指令阻止执行(点击)事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63416540/