Home >Web Front-end >JS Tutorial >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!
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"]
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.
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.
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. .
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';
##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 decoratorchangeDetection
, 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:
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.
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 of NgZone
.
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)}} 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// environment.dev.ts ... production: false ...
"optimization": false
projects > your-project-name > architect > build > configurations > dev > "optimization": false
更多编程相关知识,请访问:编程教学!!
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!