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

早过忘川 提交于 2019-12-19 10:05:04

问题


From these two posts:

  • The mechanics of DOM updates in Angular
  • Angular 2 Performance: Is it better to bind with a data member than a function?

I understand how the DOM updated when the 'Change Detection' has occurred. 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'.

Let's assume this is the parent Component view.

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

where func() is

func() { return this.parentProp }

and parentProp has not been used in the template. 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.


回答1:


Angular doesn't know or care about the content of the function.

Angular will call func() every time change detection runs and compare if the previous result is the same as the current result.

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



来源:https://stackoverflow.com/questions/49320756/how-angular-change-detection-is-triggered-when-you-are-binding-to-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!