简体   繁体   English

Angular SPA中的更改检测

[英]Change detection in Angular SPA

Consider the following very simplistic Angular SPA with the following components' tree structure: 考虑以下具有以下组件树结构的非常简单的Angular SPA:

        A
       / \
      B   C

B, C are the two pages of our SPA. B,C是我们SPA的两页。 Since B and C (their templates) can never be shown at the same time, my understanding is there is no reason to trigger change detection in C when there is model changing in B and vice versa. 由于无法同时显示BC (它们的模板),因此我的理解是there is no reason to trigger change detectionB中发生模型更改时, there is no reason to trigger change detection C中的 there is no reason to trigger change detection ,反之亦然。 As to be more clear, eg even if the changes in B affect C , there won't be any problem since when C will be shown, a brand new DOM will be built which will be aware of the prior changes and reflect them. 更清楚地说,例如即使B的更改影响C ,也不会有任何问题,因为当显示C时,将建立一个全新的DOM, will be aware of先前的更改并反映它们。

I'd appreciate your thoughts on the above . I'd appreciate your thoughts on the above Moreover, which is the best way to preclude eg C from change detection when changes apply to B ? 此外,当对B进行更改时,这是最好的方法(例如,从更改检测中排除C)

If you are using routing to display B or C, and only one or the other is activated at any point, then the other does not exist in the DOM and therefore won't get any changes. 如果使用路由显示B或C,并且在任何时候仅激活了一个,则另一个在DOM中不存在,因此不会发生任何更改。

You can try this out by adding console.log() statements in your ngOnInit and ngOnDestroy methods. 您可以通过在ngOnInitngOnDestroy方法中添加console.log()语句来进行尝试。 When you navigate to B, you'll get the ngOnInit. 导航到B时,您将获得ngOnInit。 When you navigate to C, you'll get the ngOnDestroy for B and then ngOnInit for C. 导航到C时,将为B获得ngOnDestroy ,然后为C获得ngOnInit

So the answer to your question is that you don't have to do anything to preclude C from change detection when B is loaded. 因此,您的问题的答案是,在加载B时,您无需执行任何操作即可阻止C进行更改检测。

Unless, of course, your layout is different than I assumed based on your question. 当然,除非您的布局与我根据您的问题假设的布局不同。

Here is a picture of one of my sample apps with Augury showing the component tree. 这是我的一个示例应用程序的图片,其中Augury显示了组件树。 Notice that the MovieEditComponent is not listed. 请注意,未列出MovieEditComponent。

在此处输入图片说明

And here is another screen shot after I picked the Edit option. 这是我选择“编辑”选项后的另一个屏幕截图。 Now the MovieEditComponent is listed instead of the MovieDetailComponent. 现在列出了MovieEditComponent,而不是MovieDetailComponent。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM