Reputation: 6287
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.
Upvotes: 2
Views: 1262
Reputation: 229
That's perfect! It's what you do to optimize your Change Detection. Having an OnPush strategy system will optimize for performance but most of the time the issue is Change Detection triggered too often.
Let's say you have a drag-and-drop component. You don't want to trigger Change Detection globally 10 times per second when the user is dragging. So you would want to run that in the outer zone. That being said, you might want to trigger change detection for that specific component so you would use detectChanges()
I've written to articles where running detectChanges()
in an outer zone will greatly improve the performance of your application:
Upvotes: 0
Reputation: 6287
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.
Upvotes: 2