Angular 2: ChangeDetection and mousemove event
Asked Answered
C

1

13

I have an Angular 2 Component with many children. Because of performance issues, I wanted to check how often the ChangeDetection checks my child-components. So I logged the ngAfterViewChecked-callback of one of my child-components.

I realized that my parent-component has a mousemove()-callback and so my childrens ngAfterViewChecked gets called every time I move my mouse over the parent. But I'm not updating any component variables in my mousemove()-callback. Why is the ChangeDetection running for the children then and how can I stop this?

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

Conquer answered 12/4, 2017 at 8:39 Comment(3)
This article is for youRootstock
thx so much, exactly what i was searching for!Conquer
Same for me, content where the mousemoves cause rerendering contains a Highcharts graphics.Illnatured
C
12

The site peeskillet provided 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 further information I can really recommend this article. Big THX to peeskillet!

Conquer answered 12/4, 2017 at 9:16 Comment(2)
Thanks, I tried to put zone.runOutsideAngular(.. inside the event handler. This helped me solve the problem at hand.Tartaric
It depends on what you want to do inside your event listener. Not all use-cases need a separate zone. But glad it works for you.Conquer

© 2022 - 2024 — McMap. All rights reserved.