简体   繁体   English

绑定到函数时如何触发角度变化检测?

[英]How Angular Change Detection is triggered when you are binding to a function?

From these two posts: 从这两个帖子:

I understand how the DOM updated when the 'Change Detection' has occurred. 我了解在“更改检测”发生时DOM是如何更新的。 The thing I do not understand from "Everything you need to know about change detection in Angular" is how Angular keeps track of what properties have beed used inside the function and therefore when it should run the 'Change Detection'. 我从“你需要了解的关于Angular中的变化检测的所有内容”中不了解的是Angular如何跟踪函数内部使用的属性,以及何时应该运行“更改检测”。

Let's assume this is the parent Component view. 我们假设这是父组件视图。

<child [prop]="func()"></child>

where func() is 其中func()

func() { return this.parentProp }

and parentProp has not been used in the template. parentProp尚未在模板中使用。 If and when parentProp gets changed by a service, how does the Angular knows that func() depends on parentProp and therefore should trigger a 'Change Detection' and update the view. 如果并且当parentProp被服务更改时,Angular如何知道func()依赖于parentProp ,因此应该触发“更改检测”并更新视图。

Angular doesn't know or care about the content of the function. Angular不了解或关心函数的内容。

Angular will call func() every time change detection runs and compare if the previous result is the same as the current result. Angular将在每次更改检测运行时调用func()并比较前一个结果是否与当前结果相同。

Because calling a function and comparing the result is much more expensive than just comparing the previous value with the current value, it's better to use an event to update a property with the function result and bind the view only to the property, instead of to a function directly. 因为调用函数并比较结果要比仅将前一个值与当前值进行比较要昂贵得多,所以最好使用事件来更新具有函数结果的属性,并将视图仅绑定到属性,而不是绑定到属性功能直接。

If the function returns different values on subsequent calls (with the same parameter values) you'll get an exception in development mode like 如果函数在后续调用中返回不同的值(具有相同的参数值),您将在开发模式中获得异常,例如

the model has changed since it was last checked 自上次检查后,模型已更改

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

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