Call ChangeDetectorRef.detectChanges from runOutsideAngular context. Is it ok?

Issue

Is it ok to call ChangeDetectorRef.detectChanges from NgZone.runOutsideAngular context? I have angular app that receives data via WebSocket. Websocket datastream is so intensive thereby I wrapped it into NgZone.runOutsideAngular. Various services subscribe to websocket data, process it and report their own events (Observables). They are triggered outside angular zone. Angular components subscribe to them and in event handlers (observers) call ChangeDetectorRef.detectChanges. In majority of cases this works ok. But in some cases it causes troubles: ngFor might create new elements/components out of angular zone. Event handlers of such components will trigger outsize angular.
I know I can wrap them into NgZone.run calls but this will cause global change detection that I want to avoid.

UPDATE1:
I create example to demonstrate the issue:
https://stackblitz.com/edit/angular-5-change-detection-in-runoutsideangular-context
Add some item, then try to delete it using x button.

Solution

In fact you should not run ChangeDetectorRef.detectChanges outside angular zone since if any component will be created during that checking such components will be out of angular zone, will not handle common events.

As a solution for my problem I accumulate events for short period of time (250ms) then in single NgZone.run call process them.

Answered By – Stanislav Berkov

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.