


A brief analysis of Angular's change detection mechanism and how to optimize performance?
What is change detection? The following article will take you to understand the change detection mechanism in Angular, talk about how change detection works, and introduce the performance optimization method of Angular change detection. I hope it will be helpful to everyone!
#What is change detection (Change Detection)?
The concept of change detection
After the data status in the component changes, the view needs to be updated accordingly. This mechanism for synchronizing views and data is called change detection. [Related tutorial recommendations: "angular tutorial"]
Trigger timing of change detection
As long as an asynchronous operation occurs (Events, Timer, XHR ), Angular will think that the state may have changed, and then it will perform change detection.
- Events::click, mouseover, mouseout, keyup, keydown and other browser events;
- Timer: setTimeout/setInterval;
- XHR: Various requests, etc.
Since change detection is performed on asynchronous operations, how does Angular subscribe to asynchronous requests and perform change detection?
Here is an introduction to NgZone
and its fork object Zone.js
.
Zone.js
is used to encapsulate and intercept asynchronous activities in the browser. It also provides Asynchronous life cycle hooks and unified asynchronous error handling mechanism.
Zone.js
uses Monkey Patching to intercept common methods and elements in the browser, such as setTimeout
and HTMLElement.prototype.onclick
. Angular leverages Zone.js
on startup to patch several low-level browser APIs to capture asynchronous events and call change detection after the capture time.
Angular forksZone.js
and expands its own zoneNgZone
, so that all asynchronous operations in the application will run in this zone.
How does Angular's change detection work?
Angualr will generate a change detector changeDetector
for each component to record the change status of the component.
After we create an Angular application, Angular will also create an instance of ApplicationRef
. This instance represents the instance of the Angular application we are currently creating. ApplicationRef
When created, it will subscribe to the onMicrotaskEmpty event in ngZone, and after all microtasks are completed, detectChanges()
of all views will be called to perform change detection. .
Execution order of change detection
Update the properties bound to all sub-subcomponents
Call all sub-component life cycle hooks OnChanges, OnInit, DoCheck, AfterContentInit
Update the DOM of the current component
Call the change detection of sub-components
Call the life cycle hook ngAfterViewInit of all sub-components
For example, we may encounter this kind of error when we are in development mode :
This is because change detection follows the change detection starting from the root component, from top to bottom, performing change detection for each component until the last component reaches a stable state. Before the next change detection, descendant components are not allowed to modify the properties in the parent component.
Case 1 In development mode, Angular will perform secondary detection (call enableProdMode()## in production environment #, the number of detections will be reduced to 1). Once we modify the properties of the parent component in the descendant component after
Step 4 is completed, then when Angular performs the second detection and finds that the two values are inconsistent, the above error will occur.
Case 2 As long as the parent component binds properties to the child component, no matter it is any life in OnChanges, OnInit, DoCheck, AfterContentInit and AfterViewInit Executing the following code in the cycle hook will also report an error.
// #parent {{data}} <child [data]="data"></child> // in child component ts, execute: this.parent.data = 'new Value';
Execution strategy for change detection
##Default strategy
This default strategy checks every component in the component tree from top to bottom every time an event triggers change detection (such as user events, timers, XHR, promises, etc.). This conservative checking method that does not make any assumptions about component dependencies is called Dirty Check. This strategy will have a performance impact on our application when we apply too many components.
Modify the component decorator
changeDetection
, after setting it to OnPush strategy, Angular will skip the change detection of this component and all sub-components of this component every time it triggers change detection.Under the
OnPush
strategy, only the following situations will trigger component change detection:- Input value (@Input) change (The value entered into the input must be a new reference)
- One of the current components or subcomponents triggered the event (but in the onPush strategy, the following operations will not trigger changes Detection)
- setTimeout()
- setInterval()
- Promise.resolve().then()
- this.http.get('...').subscribe()
- Manually trigger change detection (Each component will be associated with a component view ChangeDetectorRef)
- detectChanges(): It will trigger change detection of the current component and sub-components
- markForCheck(): It will not trigger change detection, but it will mark the current OnPush component and all the components whose parent component is OnPush as requiring detection status , Detect in the current or next change detection cycle
- ApplicationRef.tick(): It will trigger change detection of the entire application according to the component's change detection strategy
- async pipe
How about change detection in Angular optimization?
Since the component executes Default strategy by default, any asynchronous operation will trigger a top-to-bottom check of the entire component number. Even if the Angular team continues to improve performance and can complete hundreds of detections within milliseconds, when the application expands to hundreds or thousands of components, the change detection corresponding to the huge component tree will reach a performance bottleneck.
At this point, we need to start analyzing and reducing the number of unnecessary tests.
How to reduce the number of tests
Zone Pollution
Generally we are in life When using third-party libraries in cycle hooks, such as chart class library initialization, it will come with requestAnimationRequest/setTimeout/addEventListener. We can write the initialization method into the
runOutsideAngular
method ofNgZone
.
OnPush strategy
Views that do not involve update operations can be stripped Exit the component and use the onPush strategy to refresh the view by notifying the update (see the Execution Strategy for Change Detection section above).
##Use pure pipe instead of {{function(data)}}
In the html file, the writing method of{{function(data)}}
At this time, we can use the pipe method, Only changed values will trigger operations and update part of the view.will cause all values to be recalculated every time change detection occurs. (?: When you have a list of 1,000 items, you only modify one piece of data, but the other 999 pieces of data that do not need to be updated will also be recalculated.)
Faced with rendering a large amount of data, choose virtual scrolling/paging to request data
The above 4-point solution comes from the video introduction of the
插件:Angular devtool使用介绍
- Angular 9+, 支持Ivy。
- Guide和下载地址
- 保证运行环境为开发环境
// environment.dev.ts ... production: false ...
Copy after login - angular.json > dev配置项 >
"optimization": false
projects > your-project-name > architect > build > configurations > dev > "optimization": false
Copy after login更多编程相关知识,请访问:编程教学!!
The above is the detailed content of A brief analysis of Angular's change detection mechanism and how to optimize performance?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

This article will take you to continue learning angular and briefly understand the standalone component (Standalone Component) in Angular. I hope it will be helpful to you!

Do you know Angular Universal? It can help the website provide better SEO support!

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!
