In-depth analysis of Angular change detection mechanism
This article will explore Angular's change detection mechanism in depth, reveal its underlying operating principles, and provide optimization strategies. There is relatively little information on this topic on the Internet. This article will analyze the source code based on the latest Angular version (4.0.1 at the time of writing) and covers the applicable content of earlier versions 2.4.1.
Core concept: View (View)
Angular applications are not composed of components only, but view trees. Each component corresponds to a view, which is the basic unit in the Angular UI architecture, and is responsible for handling all property checks and DOM updates. The description of the view in the source code is as follows:
View is the basic building block of the application UI. It is the smallest grouping of elements created and destroyed together.
The properties of elements in the view can be changed, but the structure (number and order) of elements in the view cannot be changed. Changing the structure of an element can only be done by inserting, moving, or deleting nested views using ViewContainerRef. Each view can contain multiple view containers.
In this article, we use component views and component concepts interchangeably. It should be noted that many web articles and Stack Overflow answers refer to the view described here as "change detection object" or "ChangeDetectorRef". In fact, there is no separate change detection object in Angular, change detection directly acts on the view.
Each view is linked to its subview via the nodes
property, allowing actions to be performed on the subview.
View Status (ViewState)
Views have states, which play a key role in deciding whether to run change detection for a view and all of its subviews. Important states include:
FirstCheck
: Indicates whether the view is the first check. ChecksEnabled
: Indicates whether to enable change detection of the view. Errored
: Indicates whether an error occurred in the view. Destroyed
: Indicates whether the view has been destroyed. If ChecksEnabled
is false
, or the view is in the Errored
or Destroyed
state, the change detection of the view and its subviews is skipped. By default, all views are initialized with ChangeDetectionStrategy.OnPush
unless ChecksEnabled
is used.
Angular provides advanced concepts to manipulate views, such as ViewRef
, which encapsulates the underlying component view and has a detectChanges
method. When an asynchronous event occurs, Angular triggers its top-level ViewRef
change detection, which recursively detects the subview after its own change detection. ViewRef
can be injected into the component constructor through the ChangeDetectorRef
token: ViewRef
export class AppComponent { constructor(cd: ChangeDetectorRef) { ... } }
Change detection operation
checkAndUpdateView
Functions are the main logic responsible for running view change detection. The function calls itself recursively, starting from the host component, checking each component and its subcomponents in turn.
When the function is fired, it performs operations in the following order:
ViewState.firstCheck
. OnChanges
lifecycle hook of the child component is called. OnInit
and ngDoCheck
lifecycle hooks of the subcomponent (OnInit
is called only on the first check). ContentChildren
query list of subview component instances. AfterContentInit
and AfterContentChecked
lifecycle hooks of the subcomponent instance (AfterContentInit
is called only on the first check). ViewChildren
query list for the current view component instance. AfterViewInit
and AfterViewChecked
lifecycle hooks of the subcomponent instance (AfterViewInit
is called only on the first check). Change detection strategy and manual trigger
ChangeDetectionStrategy.OnPush
The policy can significantly reduce performance overhead because it only performs change detection when actual data changes, such as input attribute changes or explicit event launches.
ChangeDetectorRef
provides methods such as detectChanges()
, markForCheck()
and detach()
to enable more fine control of change detection, especially in large and complex applications.
(The following will introduce in detail the usage method of ChangeDetectorRef
and the optimization strategies for change detection, including the specific application scenarios and sample codes of the detach()
, reattach()
, markForCheck()
and detectChanges()
methods. )
(The rest of the article will continue to explore how to use these methods to optimize performance, and provide some practical application scenarios and code examples.)
(Finally, the article will summarize the frequently asked questions about Angular change detection, covering OnPush strategies, change detection optimization techniques, the role of Zones, and methods for debugging change detection.)
The above is the detailed content of Change Detection in Angular: Everything You Need to Know. For more information, please follow other related articles on the PHP Chinese website!