Home > Web Front-end > JS Tutorial > Change Detection in Angular: Everything You Need to Know

Change Detection in Angular: Everything You Need to Know

Christopher Nolan
Release: 2025-02-15 11:23:12
Original
516 people have browsed it

Change Detection in Angular: Everything You Need to Know

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:

  1. FirstCheck: Indicates whether the view is the first check.
  2. ChecksEnabled: Indicates whether to enable change detection of the view.
  3. Errored: Indicates whether an error occurred in the view.
  4. 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

The

can be injected into the component constructor through the ChangeDetectorRef token: ViewRef

export class AppComponent {
  constructor(cd: ChangeDetectorRef) { ... }
}
Copy after login

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:

  1. Set ViewState.firstCheck.
  2. Check and update the input properties of subcomponents/instructions instances.
  3. Update the subview change detection status (part of the change detection strategy implementation).
  4. Run the change detection of the embedded view (repeat the above steps).
  5. If the binding changes, the OnChanges lifecycle hook of the child component is called.
  6. Calls the OnInit and ngDoCheck lifecycle hooks of the subcomponent (OnInit is called only on the first check).
  7. Update the ContentChildren query list of subview component instances.
  8. Call the AfterContentInit and AfterContentChecked lifecycle hooks of the subcomponent instance (AfterContentInit is called only on the first check).
  9. If the properties of the current view component instance change, update the DOM interpolation of the current view.
  10. Run the change detection of the subview (repeat the above steps).
  11. Update the ViewChildren query list for the current view component instance.
  12. Call the AfterViewInit and AfterViewChecked lifecycle hooks of the subcomponent instance (AfterViewInit is called only on the first check).
  13. Disable the checking of the current view (part of the change detection policy implementation).

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template