mousemove 在 Angular 中连续触发变化检测

Don*_*Kim 7 angular

我注意到某些元素上的鼠标移动会连续触发更改检测。我研究过这个问题并发现他们建议使用runOutsideAngular的方法NgZone

所以我尝试过,

this.zone.runOutsideAngular(() => {
  this.element.addEventListener('mousemove', {});
});
Run Code Online (Sandbox Code Playgroud)

这根本不起作用。

我是否误用了runOutsideAngular或者是否有其他解决方法来防止对 mousemove 事件进行无休止的更改检测?任何见解将不胜感激!

nor*_*ico 1

@编辑对于评论问题:the canvas element rendered by a third party library

读这个

对于一般用途:

您需要使用renderer: Renderer2监听器。

请阅读这篇文章

import { Component, OnInit, OnDestroy, NgZone, Renderer2, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-mouse-tracker',
  templateUrl: './mouse-tracker.component.html',
  styleUrls: ['./mouse-tracker.component.css']
})
export class MouseTrackerComponent implements OnInit, OnDestroy {
  @ViewChild('area', { static: true }) area: ElementRef<HTMLDivElement>;
  private unlisten: Function;

  constructor(private ngZone: NgZone, private renderer: Renderer2) { }

  ngOnInit() {
    this.ngZone.runOutsideAngular(() => {
      this.unlisten = this.renderer.listen(
        this.area.nativeElement,
        'mousemove',
        () => this.drawLine()
      );
    });
  }

  ngOnDestroy() {
    this.unlisten();
  }

  drawLine() {
    console.log('Drawing a line which does not require bindings update...');
  }

  getLabel(): string {
    console.log('Label is being computed...');

    return 'exemplary label';
  }
}
Run Code Online (Sandbox Code Playgroud)

和模板:

<p>mouse-tracker works!</p>
<p>{{ getLabel() }}</p>

<div #area></div>
Run Code Online (Sandbox Code Playgroud)