Change Detection
Zone.js, change detection strategies, OnPush strategy, ChangeDetectorRef, markForCheck, detectChanges, performance optimization
1What is the change detection mechanism in Angular?
What is the change detection mechanism in Angular?
回答
Change detection is the process by which Angular detects changes in application state and updates the DOM accordingly. By default, Angular uses Zone.js to automatically detect asynchronous events (clicks, HTTP requests, timers) and triggers component checking from the root. This check traverses the component tree to identify modifications to apply to the DOM.
2What is the role of Zone.js in Angular change detection?
What is the role of Zone.js in Angular change detection?
回答
Zone.js is a library that patches native browser asynchronous APIs (setTimeout, Promise, addEventListener, etc.) to intercept their execution. When an asynchronous operation completes, Zone.js notifies Angular which automatically triggers change detection from the root component. This allows Angular to detect changes without manual developer intervention.
3What is the difference between Default and OnPush strategies?
What is the difference between Default and OnPush strategies?
回答
The Default strategy checks all components in the tree on every change detection cycle, which can be expensive. OnPush optimizes by only checking a component if its inputs change (immutable references), if an event is emitted from its template, if an async pipe receives a new value, or if markForCheck() is called manually. OnPush drastically reduces checks and improves performance.
How to enable the OnPush strategy on a component?
What is the purpose of ChangeDetectorRef in an Angular component?
+17 面接問題