绑定到函数时如何触发角度变化检测? [英] How Angular Change Detection is triggered when you are binding to a function?

查看:90
本文介绍了绑定到函数时如何触发角度变化检测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自这两个帖子:

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

我了解更改检测发生后DOM是如何更新的。从所有您需要了解的有关Angular中更改检测的信息 是Angular如何跟踪该函数内部使用了哪些属性的信息,因此它应该何时运行更改检测。

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>

其中 func()

func() { return this.parentProp }

$ b模板中未使用
$ b

parentProp 。如果并且当 parentProp 被服务更改时,Angular如何知道 func()取决于 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.

推荐答案

Angular不知道或不在乎函数的内容。

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

每次运行更改检测时,Angular都会调用 func()并比较以前的结果是否与当前结果。

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

这篇关于绑定到函数时如何触发角度变化检测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆