search
HomeWeb Front-endJS TutorialLet's talk about change detection in Angular through examples

This article will take you through the change detection in Angular. We will start with a small example, and then gradually discuss the change detection in depth. I hope it will be helpful to everyone!

Let's talk about change detection in Angular through examples

#Change detection in Angular is a mechanism used to synchronize the state of the application UI with the state of the data. When application logic changes component data, the values ​​bound to DOM properties in the view also change. The change detector is responsible for updating the view to reflect the current data model. [Recommended related tutorials: "angular tutorial"]

It is easy to learn from the paper, but I know that I have to do it in detail. In order to make it easier for readers to understand, this article starts with a small example and then expands step by step. The example is as follows:

// app.component.ts
import { Component } from '@angular/core';
@Component({  selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'aa';
    handleClick() {
        this.title = 'bb';
    }}
// app.componnet.html
<div (click)="handleClick()">{{title}}</div>

The example is relatively simple, that is, a click event is bound to the div element. Clicking on the element will change the value of the variable title. The interface The display will also update. How does the framework know when it needs to update a view, and how does it update the view? Let’s find out.

When we click on the div element, the handleClick function will be executed. So how is this function triggered in Angular applications? If you have read my previous article about the introduction of zone.js, you will know that the click event in the Angular application has been taken over by zone.js. Based on this answer, it is obvious that the execution must be triggered by zone.js at the beginning, but here we have to further analyze the direct calling relationship and expand it layer by layer. The code closest to the handleClick function call is the following code:

function wrapListener(listenerFn, ...) {
    return function wrapListenerIn_markDirtyAndPreventDefault(e) {
        let result = executeListenerWithErrorHandling(listenerFn, ...);
    }
}

The listenerFn function in the above code points to handleClick, but it Is the parameter of wrapListener function. In the example, the element is bound to a click event. The related template compilation product is probably as follows:

function AppComponent_Template(rf, ctx) { 
    ...... 
    i0["ɵɵlistener"]("click", function AppComponent_Template_div_click_0_listener() {
    return ctx.handleClick();
    })
}

When loading the application for the first time, it will execute renderView, then executeTemplate, and then trigger With the above template function, the click function of the element is passed all the way to the listenerFn parameter. At this point we understand that the trigger source of the click function is zone.js, but the actual click function delivery is implemented by Angular. So how are zone.js and Angular related? ? zone.js will arrange a task for each asynchronous event. Based on the example in this article, invokeTask is called by the following code:

function forkInnerZoneWithAngularBehavior(zone) {
    zone._inner = zone._inner.fork({
    name: &#39;angular&#39;,
    properties: { &#39;isAngularZone&#39;: true },
    onInvokeTask: (delegate, current, target, task, applyThis, applyArgs) => {
        try {
            onEnter(zone);
            return delegate.invokeTask(target, task, ...);
        }
        finally {
            onLeave(zone);
        }
    }
    })
}

See here Isn't it very familiar, because there are similar code snippets in the previous article introduced by zone.js. The forkInnerZoneWithAngularBehavior function is called by the constructor of class NgZone. So far we have introduced NgZone, a protagonist of Angular change detection, which is a simple encapsulation of zone.js.

Now that we know how the click function in the example is executed, if the application data changes after the function is executed, how can the view be updated in time? We still go back to the forkInnerZoneWithAngularBehavior function mentioned above. In the try finally statement block, the invokeTask function will eventually execute onLeave(zone )function. Further analysis can see that the onLeave function finally calls the checkStable function:

function checkStable(zone) {
    zone.onMicrotaskEmpty.emit(null);
}

is subscribed accordingly in the class ApplicationRef constructor Got this emit event:

class ApplicationRef {
    /** @internal */
    constructor() {
        this._zone.onMicrotaskEmpty.subscribe({
            next: () => {
                this._zone.run(() => {
                    this.tick();
                });
            }        
        }); 
}

In the subscription-related callback function, does this.tick() look familiar? If you have read my previous article about Angular life cycle functions, then you will definitely have the impression that it is the key call to trigger view updates. Although this function was mentioned in the life cycle introduction article, the focus of this article is change detection. Therefore, although the function is the same, the focus has changed slightly. this.tickThe relevant calling sequence is roughly like this:

this.tick() ->
view.detectChanges() -> 
renderComponentOrTemplate() ->
refreshView()

HererefreshView is more important and is analyzed separately:

function refreshView(tView, lView, templateFn, context) {
    ......
    if (templateFn !== null) {
        // 关键代码1
        executeTemplate(tView, lView, templateFn, ...);  }
    ......
    if (components !== null) {
        // 关键代码2
        refreshChildComponents(lView, components);
    }
}

In this processrefreshViewThe function will be called twice. The first time it enters the key code 2 branch, and then the following functions are called in sequence to re-enter the refreshView function:

refreshChildComponents() ->
refreshChildComponents() ->
refreshComponent() ->
refreshView()

The second time Entering the refreshView function call is the key code 1 branch, that is, the executeTemplate function is executed. And what this function ultimately executes is the AppComponent_Template function in the template compilation product:

function AppComponent_Template(rf, ctx) {
    if (rf & 1) {
        // 条件分支1
        i0["ɵɵelementStart"](0, "div", 0);
        i0["ɵɵlistener"]("click", function AppComponent_Template_div_click_0_listener() {
            return ctx.handleClick();
        });
        i0["ɵɵtext"](1);
        i0["ɵɵelementEnd"]();
    }
    if (rf & 2) {
        // 条件分支2
        i0["ɵɵadvance"](1);
        i0["ɵɵtextInterpolate"](ctx.title);
    }
}

If there are still readers who are not sure how the functions in the above template compilation product come from, it is recommended to read the previous about This article explains the principles of dependency injection and will not be repeated due to space limitations. At this time, the AppComponent_Template function executes the code in conditional branch 2, and the ɵɵadvance function is to update the relevant index value to ensure that the correct element is found. The focus here is on the ɵɵtextInterpolate function, which ultimately calls the function ɵɵtextInterpolate1:

function ɵɵtextInterpolate1(prefix, v0, suffix) {
    const lView = getLView();
    // 关键代码1
    const interpolated = interpolation1(lView, prefix, v0, suffix);
    if (interpolated !== NO_CHANGE) {
        // 关键代码2
        textBindingInternal(lView, getSelectedIndex(), interpolated);
    }
    return ɵɵtextInterpolate1;
}

值得指出的是,该函数名末尾是数字1,这是因为还有类似的ɵɵtextInterpolate2ɵɵtextInterpolate3等等,Angular 内部根据插值表达式的数量调用不同的专用函数,本文示例中文本节点的插值表达式数量为1,因此实际调用的是ɵɵtextInterpolate1函数。该函数主要做了两件事,关键代码1作用是比较插值表达式值有没有更新,关键代码2则是更新文本节点的值。先来看看关键代码1的函数interpolation1,它最终调用的是:

function bindingUpdated(lView, bindingIndex, value) {
    const oldValue = lView[bindingIndex];
    if (Object.is(oldValue, value)) {
        return false;
    }
    else {
        lView[bindingIndex] = value;
        return true;
    }
}

变更检测前的文本节点值称之为oldValue, 该值存储在lView中,lView我在之前的文章中也提到过,忘记了的读者可以去看看lView的作用。bindingUpdated首先会比较新值和旧值,比较的方法便是Object.is。如果新值旧值没有变化,则返回false。如果有变化,则更新lView中存储的值,并返回true。关键代码2的函数textBindingInternal最终调用的是下述函数:

function updateTextNode(renderer, rNode, value) {
    ngDevMode && ngDevMode.rendererSetText++;
    isProceduralRenderer(renderer) ? renderer.setValue(rNode, value) : rNode.textContent = value;
}

走完上述流程,我们点击div元素时,界面显示内容便会由aa变为bb,即完成了从应用数据的变更到 UI 状态的同步更新,这便是 Angular 最基本的变更检测过程了。

因篇幅限制,本文所举示例比较简单,但 Angular 的变更检测还有很多没有讲到。比如,如果应用是由若干个组件组成的,父子组件间的变更检测如何进行,以及如何通过策略优化变更检测等等。如果有对这方面感兴趣的朋友,欢迎关注我的个人公众号【朱玉洁的博客】,后续将在那里分享更多前端知识。

更多编程相关知识,请访问:编程学习!!

The above is the detailed content of Let's talk about change detection in Angular through examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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 Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

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),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor