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

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

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


当前回答

如果你在一个绑定到事件的方法中,简单地返回false:

@Component({
  (...)
  template: `
    <a href="/test.html" (click)="doSomething()">Test</a>
  `
})
export class MyComp {
  doSomething() {
    (...)
    return false;
  }
}

其他回答

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

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>

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

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

补充来自@AndroidUniversity的答案。在单行中你可以这样写:

<component (click)="$event.stopPropagation()"></component>

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

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

如果你在一个绑定到事件的方法中,简单地返回false:

@Component({
  (...)
  template: `
    <a href="/test.html" (click)="doSomething()">Test</a>
  `
})
export class MyComp {
  doSomething() {
    (...)
    return false;
  }
}