


A brief analysis of the DOM update mechanism in Angular change detection
Change detection is an important part of Angular, which is to maintain synchronization between the model and the view. In the daily development process, we don't need to know about change detection, because Angular helps us complete this part of the work, allowing developers to focus more on business implementation, improving development efficiency and development experience. But if you want to use the framework in depth, or if you want to write high-performance code instead of just implementing functions, you must understand change detection. It can help us better understand the framework, debug errors, improve performance, etc. [Related tutorial recommendations: "angular Tutorial"]
Angular's DOM update mechanism
Let's look at a small example first.
#When we click the button, the name attribute is changed, and the DOM is automatically updated with the new name value.
Now there is a question. If I change the value of name and then output the innerText in the DOM, what value will it be?
import { Component, ViewChild, ElementRef } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { name = 'Empty'; @ViewChild('textContainer') textContainer: ElementRef; normalClick(): void { this.name = 'Hello Angular'; console.log(this.textContainer.nativeElement.innerText); } }
Did you get the answer right?
So what exactly happened in these two pieces of code?
If we use native JS to write this code, then the view will definitely not change after clicking the button, but the view changes in Angular, then why does it automatically update the view? Woolen cloth? This is inseparable from a library called zone.js. To put it simply, it does some processing of events where values change. This will be explained in detail in the following sections. It is enough to know this for now.
If I don't want this library to do this processing, Angular also provides us with a way to disable zone.js.
You can disable zone.js in main.ts.
import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule, { ngZone: 'noop' }) .catch(err => console.error(err));
When we disable zone.js, the view is not updated. Go to the source code to find the relevant code for view update.
*/ class ApplicationRef { /** @internal */ constructor(_zone, _injector, _exceptionHandler, _initStatus) { this._zone = _zone; this._injector = _injector; this._exceptionHandler = _exceptionHandler; this._initStatus = _initStatus; /** @internal */ this._bootstrapListeners = []; this._views = []; this._runningTick = false; this._stable = true; this._destroyed = false; this._destroyListeners = []; /** * Get a list of component types registered to this application. * This list is populated even before the component is created. */ this.componentTypes = []; /** * Get a list of components registered to this application. */ this.components = []; this._onMicrotaskEmptySubscription = this._zone.onMicrotaskEmpty.subscribe({ next: () => { this._zone.run(() => { this.tick(); }); } }); ... } /** * Invoke this method to explicitly process change detection and its side-effects. * * In development mode, `tick()` also performs a second change detection cycle to ensure that no * further changes are detected. If additional changes are picked up during this second cycle, * bindings in the app have side-effects that cannot be resolved in a single change detection * pass. * In this case, Angular throws an error, since an Angular application can only have one change * detection pass during which all change detection must complete. */ tick() { NG_DEV_MODE && this.warnIfDestroyed(); if (this._runningTick) { const errorMessage = (typeof ngDevMode === 'undefined' || ngDevMode) ? 'ApplicationRef.tick is called recursively' : ''; throw new RuntimeError(101 /* RuntimeErrorCode.RECURSIVE_APPLICATION_REF_TICK */, errorMessage); } try { this._runningTick = true; for (let view of this._views) { view.detectChanges(); } if (typeof ngDevMode === 'undefined' || ngDevMode) { for (let view of this._views) { view.checkNoChanges(); } } } catch (e) { // Attention: Don't rethrow as it could cancel subscriptions to Observables! this._zone.runOutsideAngular(() => this._exceptionHandler.handleError(e)); } finally { this._runningTick = false; } } }
Broad interpretation, this ApplicationRef is an instance of the entire Angular application. In the constructor, zone (zone library) onMicrotaskEmpty (Judging from the name, it is a subject that clears microtasks) Subscribed. In the subscription, tick() is called, so what is done in tick?
Thinking: I said last time that it is best not to subscribe in the constructor. Why is it so irregular here?
Of course not. Last time we talked about which parts of Angular components should be placed in constructor and which ones should be placed in ngOnInit. But here, ApplicationRef is a service, so the initialization code can only be placed in constructor.
In the tick function, if it is found that the tick function is being executed, an exception will be thrown because this is an instance of the entire application and cannot be called recursively. Then, all views are traversed, and then each view executes detectChanges(), which means change detection is performed. What is change detection will be explained in detail later. Immediately afterwards, if it is devMode, all views are traversed again, and each view executes checkNoChanges() to check if there are any changes. If there are changes, an error will be thrown ( This issue will be discussed in detail later) , skip for now).
Okay, now I know how to update it, which is to call the tick method of ApplicationRef.
import { Component, ViewChild, ElementRef, ApplicationRef } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { name = 'Empty'; @ViewChild('textContainer') textContainer: ElementRef = {} as any; constructor(private app: ApplicationRef){} normalClick(): void { this.name = 'Hello Angular'; console.log(this.textContainer.nativeElement.innerText); this.app.tick(); } }
Sure enough, the view can be updated normally.
Let’s briefly sort it out. The update of the DOM relies on the triggering of tick(). zone.js helps developers avoid triggering this operation manually. Okay, now you can enable zone.js.
So what is change detection? Keep looking forward to the next article.
For more programming-related knowledge, please visit: Programming Teaching! !
The above is the detailed content of A brief analysis of the DOM update mechanism in Angular change detection. For more information, please follow other related articles on the PHP Chinese website!

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools