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


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 calls but this will cause global change detection that I want to avoid.

I create example to demonstrate the issue:
Add some item, then try to delete it using x button.


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 call process them.

Answered By – Stanislav Berkov

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.