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 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:
@Component({ selector: 'demo-component', template: ` <h1>{{name}}</h1> <button (click)="changeName()">change name</button> ` }) export class DemoComponent { name: string = 'Tom'; changeName() { this.name = 'Jerry'; } }
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.
@Component({ selector: 'demo-component', template: ` <h1>{{name}}</h1> ` }) export class DemoComponent implements OnInit { name: string = 'Tom'; constructor(public http: HttpClient) {} ngOnInit() { // 假设有这个./getNewName请求,返回一个新值'Jerry' this.http.get('./getNewName').subscribe((data: string) => { this.name = data; }); } }
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.
@Component({ selector: 'demo-component', template: ` <h1>{{name}}</h1> ` }) export class DemoComponent implements OnInit { name: string = 'Tom'; constructor() {} ngOnInit() { // 假设有这个./getNewName请求,返回一个新值'Jerry' setTimeout(() => { this.name = 'Jerry'; }, 1000); } }
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.
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.
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.
Child component:
@Component({ selector: 'demo-child', template: ` <h1>{{title}}</h1> <p>{{paramOne}}</p> <p>{{paramTwo}}</p> ` }) export class DemoChildComponent { title: string = '子组件标题'; @Input() paramOne: any; // 输入属性1 @Input() paramTwo: any; // 输入属性2 }
Parent component:
@Component({ selector: 'demo-parent', template: ` <h1>{{title}}</h1> <demo-child [paramOne]='paramOneVal' [paramTwo]='paramTwoVal'></demo-child> <button (click)="changeVal()">change name</button> ` }) export class DemoParentComponent { title: string = '父组件标题'; paramOneVal: any = '传递给paramOne的数据'; paramTwoVal: any = '传递给paramTwo的数据'; changeVal() { this.paramOneVal = '改变之后的传递给paramOne的数据'; } }
In the above code, DemoParentComponent passes
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.
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 之间的差别:当检测到与子组件输入绑定的值没有发生改变时,变化检测就不会深入到子组件中去。
上面说到我们可以修改组件元数据属性 changeDetection 来修改组件的变化监测策略(ChangeDetectionStrategy.Default 或 ChangeDetectionStrategy.OnPush),除了这个,我们还可以使用 ChangeDetectorRef 来更加灵活的控制组件的变化监测。
Angular 在整个运行期间都会为每一个组件创建 ChangeDetectorRef 的实例,该实例提供了相关方法来手动管理变化监测。有了这个类,我们自己就可以自定义组件的变化监测策略了,如停止/启用变化监测或者按指定路径变化监测等等。
相关方法如下:
markForCheck():把根组件到该组件之间的这条路径标记起来,通知Angular在下次触发变化监测时必须检查这条路径上的组件。
detach():从变化监测树中分离变化监测器,该组件的变化监测器将不再执行变化监测,除非再次手动执行reattach()方法。
reattach():把分离的变化监测器重新安装上,使得该组件及其子组件都能执行变化监测。
detectChanges():手动触发执行该组件到各个子组件的一次变化监测。
使用方法也很简单,直接在组件中注入即可:
@Component({ selector: 'demo-parent', template: ` <h1>{{title}}</h1> ` }) export class DemoParentComponent implements OnInit { title: string = '组件标题'; constructor(public cdRef: ChangeDetectorRef) {} ngOnInit() { this.cdRef.detach(); // 停止组件的变化监测,看需求使用不同的方法 } }
相关推荐:
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!