Angular 2: ChangeDetection and mousemove event

I have angular component 2 with many children. Due to performance issues, I wanted to check how often it ChangeDetectionchecks my child components. So I registered ngAfterViewChecked-callback of one of my child components.

I realized that my parent component has mousemove()-callback, and so my children ngAfterViewCheckedare called every time I hover over the parent. But I am not updating component variables in my mousemove()-callback. Why then ChangeDetectionworks for children and how can I stop it?

I hope you understand the problem (if not, please comment so that I can clarify things).

+9
source share
1 answer

The peeskillet site shows how to exclude EventListener from ChangeDetection:

import { Component, NgZone } from '@angular/core';

@Component(...)
export class AppComponent {
...
  element: HTMLElement;

  constructor(private zone: NgZone) {}

  mouseDown(event) {
  ...
    this.element = event.target;

    this.zone.runOutsideAngular(() => {
      window.document.addEventListener('mousemove', this.mouseMove.bind(this));
    });
  }

  mouseMove(event) {
    event.preventDefault();
    this.element.setAttribute('x', event.clientX + this.clientX + 'px');
    this.element.setAttribute('y', event.clientX + this.clientY + 'px');
  }
}

For more information, I really recommend this article . Great thx for peeskillet!

+8
source

Source: https://habr.com/ru/post/1016488/


All Articles