Home Web Front-end JS Tutorial How to optimize Angular code

How to optimize Angular code

Jun 05, 2018 pm 03:46 PM

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));
}
Copy after login

We developers will pay great attention to the order of DOM updates and the order of calling NgDoCheck and NgOnChanges. It can be found:

  1. DOM updates are depth-first

  2. 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>
Copy after login

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>
Copy after login

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>
Copy after login

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;
 }
}
Copy after login

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles