防止 Angular HostListener 传播到父组件

Prevent Angular HostListener propagation to parent component

问题

我的一个组件设置了 HostListener 绑定:

@HostListener('window:resize', ['$event']) callback ($event) {
   // D3Js tasks here …
}

目前,当侦听器被调用时,父组件会重新评估其模板,就好像父组件确实响应了某个子组件的 output
但是从侦听器执行的任务不需要父组件的任何更新。

我希望监听器可以在不通知父组件的情况下执行。

可以防止这种冒泡行为在Angular的某处在这种情况下吗?

尝试次数

$event.stopPropagation()$event.stopImmediatePropagation() 都没有帮助,可能是因为此行为与 Angular 内部机制有关。
HostListener 声明留空(注释掉包含的指令)不会改变任何东西,在我看来这表明 HostListener 声明是这里的罪魁祸首。

我目前的解决方案是在组件构造函数中直接从原生 DOM 事件创建一个可观察对象(不依赖 Angular):

this.onResizeSub = Observable
    .fromEvent(window, 'resize', null, null)
    .subscribe( () => {…});
);

注意:使用 Angular v4.4.2,在所有地方更改检测 OnPush 策略。

不幸的是,Angular 目前似乎不支持此功能。有一个功能请求,但看起来我们不会很快看到它:https://github.com/angular/angular/issues/9587, https://github.com/angular/angular/issues/10990

The order of execution is red herring - the order in which an event on the same element is propagated to multiple listeners is currently undefined. this is currently by design.

Your problem is that the event exposed to the listeners is the real DOM event and calling stopImmediatePropagation() on the provided event stops execution of other listeners registered on this element. However since all the the listeners registered via Angular are proxied by just a single dom listener (for performance reasons) calling stopImmediatePropagation on this event has no effect.