Home >Web Front-end >JS Tutorial >How to optimize Angular code
This time I will bring you how to optimize Angular code and what are the precautions for optimizing Angular code. The following is a practical case, let's take a look.
Summary
Angular 4’s dirty value detection is an old topic, and understanding this model is the basis for Angular performance optimization. Therefore, today we will talk about the principle of dirty value detection in Angular 4 and look at some tips for performance optimization.
Entry Point - Zone.js
Angular 4 is an MVVM framework. After the data model (Model) is converted into a view model (ViewModel), it is bound to the view (View) and rendered into a page visible to the naked eye. Therefore, discovering the time point when the data model changes is the key to updating the page and calling dirty value detection.
After analysis, engineers found that data changes are often caused by asynchronous events such as macrotask and microtask. Therefore, by rewriting all asynchronous APIs in the browser, data changes can be effectively monitored from the source. Zone.js is such a monkey script (Monkey Patch). Angular 4 uses a customized Zone (NgZone), which notifies Angular that there may be data changes and needs to update the data in the view (dirty value detection).
Dirty value detection (Change Detection)
The basic principle of dirty value detection is to store the old value, and when detecting, compare the new value at the current moment with the old value Value comparison. If they are equal, there is no change. Otherwise, a change is detected and the view needs to be updated.
Angular 4 divides the page into several Components to form a component tree. After entering the dirty value detection, the detection is performed from top to bottom from the root component. Angular has two strategies: Default and OnPush. They are configured on the component and determine different behaviors during dirty value detection.
Default - The default strategy
ChangeDetectionStrategy.Default. It also means that this component is always tested once an event occurs that may change the data.
The operation of dirty value detection can basically be understood as the following steps. 1) Update the properties bound to the subcomponent, 2) Call the NgDoCheck and NgOnChanges lifecycle hooks of the subcomponent, 3) Update its own DOM, 4) Detect the dirty value of the subcomponent. This is a recursive equation starting from the root component.
// This is not Angular code function changeDetection(component) { updateProperties(component.children); component.children.forEach(child => { child.NgDoCheck(); child.NgOnChanges(); }; updateDom(component); component.children.forEach(child => changeDetection(child)); }
We developers will pay great attention to the order of DOM updates and the order of calling NgDoCheck and NgOnChanges. It can be found:
DOM updates are depth-first
NgDoCheck and NgOnChanges are not (nor are they depth-first)
OnPush - Single detection strategy
ChangeDetectionStrategy.OnPush. This component is only detected when the Input Properties change (OnPush). Therefore, when the Input does not change, it is only detected during initialization, also called a single detection. Its other behavior is consistent with Default.
It should be noted that OnPush only detects Input references. Property changes of the Input object will not trigger dirty value detection of the current component.
Although the OnPush strategy improves performance, it is also a hot spot for bugs. The solution is often to convert Input into Immutable form and force the reference of Input to change.
Tips
Data Binding
Angular has 3 legal ways of data binding, but their performance is Different.
Bind data directly
<ul> <li *ngFor="let item of arr"> <span>Name {{item.name}}</span> <span>Classes {{item.classes}}</span><!-- Binding a data directly. --> </li> </ul>
In most cases, this is the best way to perform.
Bind a function call result
<ul> <li *ngFor="let item of arr"> <span>Name {{item.name}}</span> <span>Classes {{classes(item)}}</span><!-- Binding an attribute to a method. The classes would be called in every change detection cycle --> </li> </ul>
In each dirty value detection process, the classes equation must be called once. Imagine that the user is scrolling the page, multiple macrotask are generated, and each macrotask performs at least one dirty value check. If there are no special needs, this method of use should be avoided as much as possible.
Bind data pipe
<ul> <li *ngFor="let item of instructorList"> <span>Name {{item.name}}</span> <span>Classes {{item | classPipe}}</span><!-- Binding data with a pipe --> </li> </ul>
It is similar to the binding function. Every time the dirty value detection classPipe is called. However, Angular has optimized the pipe and added caching. If the item is equal to the last time, the result will be returned directly.
NgFor
In most cases, NgFor should be used with the trackBy equation. Otherwise, NgFor will update the DOM for each item in the list during each dirty value detection process.
@Component({ selector: 'my-app', template: ` <ul> <li *ngFor="let item of collection;trackBy: trackByFn">{{item.id}}</li> </ul> <button (click)="getItems()">Refresh items</button> `, }) export class App { collection; constructor() { this.collection = [{id: 1}, {id: 2}, {id: 3}]; } getItems() { this.collection = this.getItemsFromServer(); } getItemsFromServer() { return [{id: 1}, {id: 2}, {id: 3}, {id: 4}]; } trackByFn(index, item) { return index; } }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to separate configuration data from code
How to detect properties in web development
The above is the detailed content of How to optimize Angular code. For more information, please follow other related articles on the PHP Chinese website!