Table of Contents
What is change monitoring
The source of change monitoring
Events: click/hover/...
XHR/webSocket
Times: setTimeout/requestAnimationFrame
Summary
Change monitoring processing mechanism
For example
Change Monitoring Strategy
变化监测类 - ChangeDetectorRef
Home Web Front-end JS Tutorial Angular Development Practice (5): In-depth Analysis of Change Monitoring

Angular Development Practice (5): In-depth Analysis of Change Monitoring

Apr 02, 2018 pm 03:03 PM
angular go deep parse

What is change monitoring

In developing with Angular, we often use binding in Angular - input binding from model to view, output binding from view to model, and binding between view and model Two-way binding. The reason why these bound values ​​can be synchronized between the view and the model is due to the change detection in Angular.

Simply put, change detection is used by Angular to detect whether the values ​​bound between the view and the model have changed. When it is detected that the values ​​bound in the model have changed, it is synchronized to the view. On the contrary, when it is detected that the bound value on the view changes, the corresponding binding function is called back.

The source of change monitoring

The key to change monitoring is how to monitor whether the bound values ​​have changed at the smallest granularity, and under what circumstances will these bound values ​​change? Woolen cloth? We can take a look at some of our commonly used scenarios:

Events: click/hover/...

@Component({
  selector: 'demo-component',
  template: `
    <h1>{{name}}</h1>
    <button (click)="changeName()">change name</button>
  `
})
export class DemoComponent {
    name: string = &#39;Tom&#39;;
    
    changeName() {
        this.name = &#39;Jerry&#39;;
    }
}
Copy after login

We bind the name attribute in the template through interpolation expressions. When the change name button is clicked, the value of the name attribute is changed, and the display content of the template view also changes.

XHR/webSocket

@Component({
  selector: &#39;demo-component&#39;,
  template: `
    <h1>{{name}}</h1>
  `
})
export class DemoComponent implements OnInit {
    name: string = &#39;Tom&#39;;
    
    constructor(public http: HttpClient) {}
    
    ngOnInit() {
        // 假设有这个./getNewName请求,返回一个新值&#39;Jerry&#39;
        this.http.get(&#39;./getNewName&#39;).subscribe((data: string) => {
            this.name = data;
        });
    }
}
Copy after login

We sent an Ajax request to the server in the ngOnInit function of this component. When the request returns the result, it will also change the binding on the current template view. The value of the name attribute.

Times: setTimeout/requestAnimationFrame

@Component({
  selector: &#39;demo-component&#39;,
  template: `
    <h1>{{name}}</h1>
  `
})
export class DemoComponent implements OnInit {
    name: string = &#39;Tom&#39;;
    
    constructor() {}
    
    ngOnInit() {
        // 假设有这个./getNewName请求,返回一个新值&#39;Jerry&#39;
        setTimeout(() => {
            this.name = &#39;Jerry&#39;;
        }, 1000);
    }
}
Copy after login

We set a scheduled task in the ngOnInit function of this component. When the scheduled task is executed, the name attribute bound to the current view will also be changed. value.

Summary

  • In fact, it is not difficult for us to find that the above three situations have one thing in common, that is, these events that cause the binding value to change all occur asynchronously. .

  • Angular does not capture changes in objects. It uses the appropriate timing to check whether the value of the object has been changed. This timing is the occurrence of these asynchronous events.

  • This timing is controlled by the NgZone service. It obtains the execution context of the entire application, can capture the occurrence, completion or exception of relevant asynchronous events, and then drives Angular Implementation of change monitoring mechanism.

Change monitoring processing mechanism

Through the above introduction, we roughly understand how change detection is triggered, then how change monitoring in Angular is performed Woolen cloth?

First of all, what we need to know is that for each component, there is a corresponding change detector; that is, each Component corresponds to a changeDetector, we can pass dependencies in the Component Inject to get changeDetector.

And our multiple Components are organized in a tree structure. Since one Component corresponds to a changeDetector, then the changeDetector also has a tree structure. organize.

The last thing we need to remember is that every change monitoring starts from the root of the Component tree.

For example

Child component:

@Component({
  selector: &#39;demo-child&#39;,
  template: `
    <h1>{{title}}</h1>
    <p>{{paramOne}}</p>
    <p>{{paramTwo}}</p>
  `
})
export class DemoChildComponent {
    title: string = &#39;子组件标题&#39;;
    @Input() paramOne: any; // 输入属性1
    @Input() paramTwo: any; // 输入属性2
}
Copy after login

Parent component:

@Component({
  selector: &#39;demo-parent&#39;,
  template: `
    <h1>{{title}}</h1>
    <demo-child [paramOne]=&#39;paramOneVal&#39; [paramTwo]=&#39;paramTwoVal&#39;></demo-child>
    <button (click)="changeVal()">change name</button>
  `
})
export class DemoParentComponent {
    title: string = &#39;父组件标题&#39;;
    paramOneVal: any = &#39;传递给paramOne的数据&#39;;
    paramTwoVal: any = &#39;传递给paramTwo的数据&#39;;
    
    changeVal() {
        this.paramOneVal = &#39;改变之后的传递给paramOne的数据&#39;;
    }
}
Copy after login

In the above code, DemoParentComponent passes < The /demo-child> tag is embedded with DemoChildComponent. From a tree structure perspective, DemoParentComponent is the root node of DemoChildComponent, and DemoChildComponent is the leaf node of DemoParentComponent.

When we click the button of DemoParentComponent, it will be called back to the changeVal method, and then the execution of change monitoring will be triggered. The change monitoring process is as follows:

First change detection starts from DemoParentComponent Start:

  • Detect whether the value of title has changed: No change has occurred

  • Detect whether the value of paramOneVal has changed: Change has occurred (click The button calls the changeVal() method to change)

  • Detect whether the paramTwoVal value has changed: no change has occurred

Then change detection enters the leaf Node DemoChildComponent:

  • Detect whether the title value has changed: no change

  • Detect whether paramOne has changed: it has changed (due to The property paramOneVal of the parent component has changed)

  • Detect whether paramTwo has changed: No change has occurred

Finally, because DemoChildComponent no longer exists Leaf nodes, so change monitoring will update the DOM and synchronize changes between the view and the model.

Change Monitoring Strategy

After learning the processing mechanism of change monitoring, you may think that this mechanism is a bit too simple and crude. If there are hundreds or thousands of files in my application, If any Component triggers monitoring, it needs to be re-detected from the root node to the leaf node.

Don’t worry, Angular’s ​​development team has already considered this issue. The above detection mechanism is just a default detection mechanism. Angular also provides an OnPush detection mechanism (set the metadata attribute changeDetection: ChangeDetectionStrategy.OnPush ).

OnPush 与 Default 之间的差别:当检测到与子组件输入绑定的值没有发生改变时,变化检测就不会深入到子组件中去

变化监测类 - ChangeDetectorRef

上面说到我们可以修改组件元数据属性 changeDetection 来修改组件的变化监测策略(ChangeDetectionStrategy.Default 或 ChangeDetectionStrategy.OnPush),除了这个,我们还可以使用 ChangeDetectorRef 来更加灵活的控制组件的变化监测。

Angular 在整个运行期间都会为每一个组件创建 ChangeDetectorRef 的实例,该实例提供了相关方法来手动管理变化监测。有了这个类,我们自己就可以自定义组件的变化监测策略了,如停止/启用变化监测或者按指定路径变化监测等等。

相关方法如下:

  • markForCheck():把根组件到该组件之间的这条路径标记起来,通知Angular在下次触发变化监测时必须检查这条路径上的组件。

  • detach():从变化监测树中分离变化监测器,该组件的变化监测器将不再执行变化监测,除非再次手动执行reattach()方法。

  • reattach():把分离的变化监测器重新安装上,使得该组件及其子组件都能执行变化监测。

  • detectChanges():手动触发执行该组件到各个子组件的一次变化监测。

使用方法也很简单,直接在组件中注入即可:

@Component({
  selector: &#39;demo-parent&#39;,
  template: `
    <h1>{{title}}</h1>
  `
})
export class DemoParentComponent implements OnInit {
    title: string = &#39;组件标题&#39;;
    
    constructor(public cdRef: ChangeDetectorRef) {}
    
    ngOnInit() {
        this.cdRef.detach(); // 停止组件的变化监测,看需求使用不同的方法
    }
}
Copy after login

相关推荐:

Angular开发实践(四):组件之间的交互

Angular开发实践(二):HRM运行机制

         

The above is the detailed content of Angular Development Practice (5): In-depth Analysis of Change Monitoring. 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)

A deep dive into the meaning and usage of HTTP status code 460 A deep dive into the meaning and usage of HTTP status code 460 Feb 18, 2024 pm 08:29 PM

In-depth analysis of the role and application scenarios of HTTP status code 460 HTTP status code is a very important part of web development and is used to indicate the communication status between the client and the server. Among them, HTTP status code 460 is a relatively special status code. This article will deeply analyze its role and application scenarios. Definition of HTTP status code 460 The specific definition of HTTP status code 460 is "ClientClosedRequest", which means that the client closes the request. This status code is mainly used to indicate

iBatis and MyBatis: Comparison and Advantage Analysis iBatis and MyBatis: Comparison and Advantage Analysis Feb 18, 2024 pm 01:53 PM

iBatis and MyBatis: Differences and Advantages Analysis Introduction: In Java development, persistence is a common requirement, and iBatis and MyBatis are two widely used persistence frameworks. While they have many similarities, there are also some key differences and advantages. This article will provide readers with a more comprehensive understanding through a detailed analysis of the features, usage, and sample code of these two frameworks. 1. iBatis features: iBatis is an older persistence framework that uses SQL mapping files.

Detailed explanation of Oracle error 3114: How to solve it quickly Detailed explanation of Oracle error 3114: How to solve it quickly Mar 08, 2024 pm 02:42 PM

Detailed explanation of Oracle error 3114: How to solve it quickly, specific code examples are needed. During the development and management of Oracle database, we often encounter various errors, among which error 3114 is a relatively common problem. Error 3114 usually indicates a problem with the database connection, which may be caused by network failure, database service stop, or incorrect connection string settings. This article will explain in detail the cause of error 3114 and how to quickly solve this problem, and attach the specific code

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

Analysis of the meaning and usage of midpoint in PHP Analysis of the meaning and usage of midpoint in PHP Mar 27, 2024 pm 08:57 PM

[Analysis of the meaning and usage of midpoint in PHP] In PHP, midpoint (.) is a commonly used operator used to connect two strings or properties or methods of objects. In this article, we’ll take a deep dive into the meaning and usage of midpoints in PHP, illustrating them with concrete code examples. 1. Connect string midpoint operator. The most common usage in PHP is to connect two strings. By placing . between two strings, you can splice them together to form a new string. $string1=&qu

Parsing Wormhole NTT: an open framework for any Token Parsing Wormhole NTT: an open framework for any Token Mar 05, 2024 pm 12:46 PM

Wormhole is a leader in blockchain interoperability, focused on creating resilient, future-proof decentralized systems that prioritize ownership, control, and permissionless innovation. The foundation of this vision is a commitment to technical expertise, ethical principles, and community alignment to redefine the interoperability landscape with simplicity, clarity, and a broad suite of multi-chain solutions. With the rise of zero-knowledge proofs, scaling solutions, and feature-rich token standards, blockchains are becoming more powerful and interoperability is becoming increasingly important. In this innovative application environment, novel governance systems and practical capabilities bring unprecedented opportunities to assets across the network. Protocol builders are now grappling with how to operate in this emerging multi-chain

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

Analysis of new features of Win11: How to skip logging in to Microsoft account Analysis of new features of Win11: How to skip logging in to Microsoft account Mar 27, 2024 pm 05:24 PM

Analysis of new features of Win11: How to skip logging in to a Microsoft account. With the release of Windows 11, many users have found that it brings more convenience and new features. However, some users may not like having their system tied to a Microsoft account and wish to skip this step. This article will introduce some methods to help users skip logging in to a Microsoft account in Windows 11 and achieve a more private and autonomous experience. First, let’s understand why some users are reluctant to log in to their Microsoft account. On the one hand, some users worry that they

See all articles