Javascript 角度-是否可以通过指令阻止执行(单击)事件?
我创建了以下指令,我想防止在某些条件下执行Javascript 角度-是否可以通过指令阻止执行(单击)事件?,javascript,angular,Javascript,Angular,我创建了以下指令,我想防止在某些条件下执行(单击)事件(或延迟单击,或要求用户确认等)。出于演示目的,我下面的目标是完全阻止执行事件: import { Directive, HostListener } from '@angular/core'; @Directive({ selector: '[disabledButton]' }) export class DisabledButtonDirective { @HostListener('click', ['$event'])
(单击)
事件(或延迟单击,或要求用户确认等)。出于演示目的,我下面的目标是完全阻止执行事件:
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>
推我
在上面的相同内容中,我希望不执行
shouldnotbexecuted()
方法。但它是…我认为,当前代码没有问题preventDefault
-只需防止默认操作,例如,对于链接,它将引导您到另一个路由,等等停止传播
-防止通过DOM树传播
解决此问题的一些方法是将按钮设置为disabled(禁用)或check(检查),该事件为Prevented(预防)默认:
<button (click)="shouldNotBeExecuted($event)" disabledButton>Push Me</button>
@Component({
selector: "app",
templateUrl: "./app.component.html"
})
export class AppComponent {
shouldNotBeExecuted(event: MouseEvent): void {
if(event.defaultPrevented ) {
console.log('prevented');
}
}
}
推我
@组成部分({
选择器:“应用程序”,
templateUrl:“./app.component.html”
})
导出类AppComponent{
不应执行(事件:MouseEvent):无效{
如果(event.defaultPrevented){
console.log('prevented');
}
}
}
您可以使用“禁用”属性来防止单击
<button (click)="shouldNotBeExecuted()" [disabled]="your condition here">Push Me</button>
推我
如果将按钮设置为组件,则可以为回调使用不同的属性,以便控制何时调用它
<fancy-button (onPress)="shouldNotBeExecuted()">
Press Me
</fancy-button>
按我
是的,这是可能的:
@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();
}
}
已经完成!对不起,最初我没有接受答案,而是投了更高的票。