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

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

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


当前回答

试试这个指令

@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']" />

其他回答

我使用

<... (click)="..;..; ..someOtherFunctions(mybesomevalue); $event.stopPropagation();" ...>...

简而言之,只需用';'分隔其他事物/函数调用,并添加$event.stopPropagation()

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

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

最简单的方法是在事件处理程序上调用停止传播。$event在Angular 2中的工作原理是一样的,它包含了正在发生的事件(鼠标点击、鼠标事件等等):

(click)="onEvent($event)"

在事件处理程序中,我们可以停止传播:

onEvent(event) {
   event.stopPropagation();
}

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

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

试试这个指令

@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']" />