title: Angular Mouseover Events Preventing Change Detection Updating The Template
body: <p>Angular v12.2,
  NgRx v12.4,
  RxJs v6.6.0</p>
  <hr />
  <p>I am developing an Angular web app and one part of it displays a data bound grid of approximately 300 squares. A little like a chess board. As the user moves the mouse over the grid I display some data relating to the individual square the mouse is hovering over. However, no matter what I try the displayed data lags behind the mouse and only updates when the mouse slows or stops. Curiously I am following a method which I successfully adopted for another project which is really performant but was using Angular v10, NgRx v10.</p>
  <p>The grid of components is a simple <code>*ngFor=&quot;let location of locations; let i = index; trackBy:locationTrackByFunction&quot;</code>.</p>
  <p>I have chosen to create a <code>mouse-tracker</code> component which sits above my grid and its only responsibility is to get the mouse <code>offsetX</code> and <code>offsetY</code> and emit events outside of the Angular Zone for the <code>mouse-tracker-container</code> parent component to receive. I did this to minimise the change detection being triggered for every change in the mousemove event. My <code>mouse-tracker</code> template is as follows:</p>
  <pre><code>&lt;div #eventDiv id=&quot;mouse-tracker&quot;&gt;&lt;/div&gt;
  </code></pre>
  <p>The code is as follows:</p>
  <pre><code>  @ViewChild('eventDiv', { static: true }) eventDiv!: ElementRef;
  
    @Output() mouseMove = new EventEmitter();
  
    private move$: Observable&lt;MouseEvent&gt; | undefined;
    private leave$: Observable&lt;MouseEvent&gt; | undefined;
    private moveSubscription: Subscription = new Subscription;
  
    constructor(private ngZone: NgZone) {}
  
    ngOnInit() {}
  
    ngOnDestroy(): void {
      this.moveSubscription.unsubscribe();
    }
  
    ngAfterViewInit() {
  
      const eventElement = this.eventDiv.nativeElement;
  
      this.move$ = fromEvent(eventElement, 'mousemove');
      this.leave$ = fromEvent(eventElement, 'mouseleave');
  
      /*
       * We are going to detect mouse move events outside of
       * Angular's Zone to prevent Change Detection every time
       * a mouse move event is fired.
       */
      this.ngZone.runOutsideAngular(() =&gt; {
  
        // Check we have a move$ and leave$ objects.
        if (this.move$ &amp;&amp; this.leave$) {
  
          // Configure moveSubscription.
          this.moveSubscription = this.move$.pipe(
            takeUntil(this.leave$),
            repeat(),
          ).subscribe((e: MouseEvent) =&gt; {
            //e.stopPropagation();
            e.preventDefault();
            this.mouseMove.emit(e);
  
          });
        };
  
      });
  
    };
  </code></pre>
  <p>The <code>mouseMove</code> event is received by the hosting <code>grid</code> component and it simply emits its own event passing the data back to its own <code>grid-container</code> parent as follows:</p>
  <pre><code>public onMouseMove(e: MouseEvent) {
    this.mouseMove.emit(e);
  };
  </code></pre>
  <p>The <code>grid-container</code> component, on receiving the <code>mouseMove</code> event simply updates an RxJs Subject as follows:</p>
  <pre><code>public onMouseMove(e: MouseEvent) {
      this.mouseOffsetsSubject$.next({ x: e.offsetX, y: e.offsetY });
  };
  </code></pre>
  <p>The <code>mouseoverLocationSubject$</code> along with two other Observables are brought together in an RxJs <code>CombineLatest</code> and ultimately after performing some calculations Dispatch an NgRx Action every time the mouse is over a different location (using <code>distinctUntilChanged()</code>) in the Angular Zone (to implement change detection) as follows:</p>
  <pre><code>this.ngZone.run(() =&gt; {
  
            if (location !== null) {
  
              // Dispatch an NgRx Action to save the Location in the Store.
              this.store.dispatch(fromCoreActions.LocationActions.setMouseoverLocationId(
                { mouseoverLocationId: location.id }
              ));
  
            }
            else {
  
              // Dispatch an NgRx Action to save the Location in the Store.
              this.store.dispatch(fromCoreActions.LocationActions.setMouseoverLocationId(
                { mouseoverLocationId: null }
              ));
  
            };
  
          });
  </code></pre>
  <p>If I console log out the code in the reducer, or use the Redux dev tools in Chrome, I can see the NgRx Store being rapidly updated. No problem.</p>
  <p>A <code>location-display</code> component is responsible for displaying the name of the mouse-over location. Its parent <code>location-display-container</code> component has an Observable being updated by the changing NgRx Selector as follows:</p>
  <pre><code>public mouseoverLocation$: Observable&lt;Location | null&gt;;
  ...
  this.mouseoverLocation$ = this.store.pipe(
    select(fromCoreSelectors.locationSelectors.selectMouseoverLocation),
    tap(location =&gt; {
      //console.log(`mouseoverLocation$: ${location?.name}`);
    })
  );
  </code></pre>
  <p>If I un-comment the <code>console.log()</code> the changing stream of data being received is rapid and closely matches the moving mouse. No delays up to here.</p>
  <p>A simple async pipe passes the mouseoverLocation object to the child component <code>[mouseoverLocation]=&quot;mouseoverLocation$ | async&quot;</code> which receives the object <code>@Input() mouseoverLocation: Location | null = null;</code> and actually displays the data in the template using interpolation as follows:</p>
  <pre><code>      &lt;div fxFlex=&quot;{{lineHeight}}px&quot;&gt;
          &lt;div fxLayout=&quot;row&quot; fxLayoutGap=&quot;8px&quot;&gt;
            &lt;div fxFlex=&quot;200px;&quot; class=&quot;mouse-over-sub-hdg&quot;&gt;Location: &lt;/div&gt;
            &lt;div fxFlex&gt;{{mouseoverLocation?.name}}&lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
  </code></pre>
  <p>When run, both in developer and production builds, the displayed value lags badly behind the mouse and does not at all match the stream of data being received in the Observable. In fact if I circle the mouse over the grid so it never stops moving the template does not update at all. Only when I slow the mouse or stop does it jump to the value of the square the mouse is over.</p>
  <p>I have tried refactoring this in many different ways including forcing change detection as each new value is received by the Observable <code>cdRef.markForCheck()</code> and <code>cdRef.detectChanges()</code>. I tried creating a <code>@ViewChild</code> of the <code>location-display</code> component and directly updating the mouseoverLocation value. I tried using the <code>ngrxPush</code> pipe. Every time the same result. All components implement <code>OnPush</code>.</p>
  <p>I removed all the Zone related code thinking that this may be the root of the problem, but it lagged just the same, though I could see the considerable increase in change detection for every mousemove event.</p>
  <p>Perhaps Chrome's DevTools Performance tab may provide a clue but honestly I can't get my head around how to use it.</p>
  <p>Any advise, thoughts or suggestions very welcome. Thank you.</p>