We have a number of components in our Angular application that need to regularly display new values every second that are unique to each component (countdowns, timestamps, elapsed time, etc). The most natural way to is to create observables that use the RxJS timer
and interval
factory functions. However, these trigger Angular change detection at every interval for the entire app as many times as the interval function was called. If we have dozens of components on the page, this triggers change detection for the entire app dozens of times every second or time period, creating a large performance overhead.
So far there are two ways I've attempted to solve the problem. A good answer to either would be very helpful - ideally both. I want to avoid manual trigger of change detection and instead rely on new values emitted from Observables and have the async pipe/OnPush change detection strategy be responsible for triggering change detection. If this isn't possible, I'd like to understand why.
- Is there any way to disable or prevent RxJS
timer
orinterval
functions from triggering Angular change detection? Using NgZonezone.runOutsideAngular(() => this.interval$ = interval(1000) ... )
does not appear to do this. StackBlitz example: https://stackblitz.com/edit/angular-zo5h39 - Alternatively, if I create an Observable stream using an RxJS
Subject
combined withsetInterval
called insidezone.runOutsideAngular
, why isn't change detection triggered for the child component when a new value is emitted from the subject? StackBlitz example: https://stackblitz.com/edit/angular-yxdjgd