在Angular中停止鼠标事件传播的最简单方法是什么?

我应该传递特殊的$event对象和调用stopPropagation()自己或有一些其他的方式。

例如,在Meteor中,我可以简单地从事件处理程序返回false。


当前回答

我刚刚检查了一个Angular 6应用程序,event. stoppropagation()在一个事件处理程序上工作,甚至不需要传递$event

(click)="doSomething()"  // does not require to pass $event


doSomething(){
   // write any code here

   event.stopPropagation();
}

其他回答

试试这个指令

@Directive({
    selector: '[stopPropagation]'
})
export class StopPropagationDirective implements OnInit, OnDestroy {
    @Input()
    private stopPropagation: string | string[];

    get element(): HTMLElement {
        return this.elementRef.nativeElement;
    }

    get events(): string[] {
        if (typeof this.stopPropagation === 'string') {
            return [this.stopPropagation];
        }
        return this.stopPropagation;
    }

    constructor(
        private elementRef: ElementRef
    ) { }

    onEvent = (event: Event) => {
        event.stopPropagation();
    }

    ngOnInit() {
        for (const event of this.events) {
            this.element.addEventListener(event, this.onEvent);
        }
    }

    ngOnDestroy() {
        for (const event of this.events) {
            this.element.removeEventListener(event, this.onEvent);
        }
    }
}

使用

<input 
    type="text" 
    stopPropagation="input" />

<input 
    type="text" 
    [stopPropagation]="['input', 'click']" />

这解决了我的问题,从防止一个事件被一个孩子触发:

doSmth () { // what ever } < div(点击)= " doSmth ()" > < div(点击)= " $ event.stopPropagation ()" > <组件> < /组件> < / div > < / div >

IE (Internet Explorer)什么都不行。我的测试人员可以通过点击后面弹出窗口的按钮来破坏我的模式。所以,我听了我的模式屏幕div的点击声,并强制重新聚焦在一个弹出按钮上。

<div class="modal-backscreen" (click)="modalOutsideClick($event)">
</div>


modalOutsideClick(event: any) {
   event.preventDefault()
   // handle IE click-through modal bug
   event.stopPropagation()
   setTimeout(() => {
      this.renderer.invokeElementMethod(this.myModal.nativeElement, 'focus')
   }, 100)
} 

在函数后添加false将停止事件传播

<a (click)="foo(); false">click with stop propagation</a>

如果您希望能够将此添加到任何元素,而不必一遍又一遍地复制/粘贴相同的代码,您可以制作一个指令来完成此操作。如下图所示:

import {Directive, HostListener} from "@angular/core";
    
@Directive({
    selector: "[click-stop-propagation]"
})
export class ClickStopPropagation
{
    @HostListener("click", ["$event"])
    public onClick(event: any): void
    {
        event.stopPropagation();
    }
}

然后将它添加到你想要它的元素:

<div click-stop-propagation>Stop Propagation</div>