wasAsked.

what is change detection strategy? is default strategy is good or change detection is better?

EY · Role not specified · technical

Published

Year not specified · Angular

Community answers

Posted by wasAsked editorial collection

Change detection is how Angular keeps the DOM in sync with component data. After an event (click, HTTP response, timer), Angular checks components and updates bindings whose values changed. Default strategy (ChangeDetectionStrategy.Default) - With Zone.js, any asynchronous event triggers a check of the whole component tree from the root. - Advantage: it "just works", even when you mutate objects directly. - Disadvantage: in large applications, many components are checked unnecessarily, which costs CPU time, especially with complex templates or frequent events. OnPush strategy (ChangeDetectionStrategy.OnPush) @Component({ selector: 'app-product-card', changeDetection: ChangeDetectionStrategy.OnPush, ... }) A component (and its subtree) is checked only when: - an @Input reference changes (a new object or value, not a mutation), - an event originates from the component or its children, - an Observable used with the async pipe emits, - a signal read in the template changes, - or you call ChangeDetectorRef.markForCheck() manually. Which is better? For most applications, OnPush is better for performance and also encourages a cleaner design: - Use immutable updates (this.items = [...this.items, newItem] instead of push). - Prefer the async pipe and signals for data flowing into templates. But OnPush requires discipline: mutating an object in place will not update the view, which can confuse teams unfamiliar with it. A common approach is to use OnPush for presentational and list components, and default only where it is genuinely simpler. Where Angular is heading Signals give Angular precise knowledge of what changed, and newer versions support zoneless change detection (provideZonelessChangeDetection), where Zone.js is removed and updates are driven by signals, the async pipe and explicit notifications. OnPush plus signals is the natural preparation for zoneless apps. Debugging tip: Angular DevTools' profiler shows how many components are checked per cycle, which quickly proves the benefit of OnPush.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics