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

不言
Release: 2018-04-02 15:03:18
Original
1345 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template