Angular - Is binding a component method to DOM target property a wrong practice?

醉酒当歌 提交于 2019-12-05 15:19:59

It's fine to use a method call as an expression if you know what you're doing. Here is the quote from the docs:

Although it's possible to write quite complex template expressions, you should avoid them.

A property name or method call should be the norm.

As you noticed Angular executes expressions on each change detection run, so your function will be executed quite often:

Angular executes template expressions after every change detection cycle. Change detection cycles are triggered by many asynchronous activities such as promise resolutions, http results, timer events, keypresses and mouse moves.

So it's still better to try to replace a method call with direct property access in the expression. If your function does the following:

getHealth() {
   return this.health;
}

You can put:

[health]="health"

Read more about change detection here:

In data binding expressions, we can call functions, but they must be side effects free. Here is the official guidelines to write data binding expressions.

Since Angular change detection is based on unidirectional data flow strategy, changing application state in a data binding expression, can cause incoherence between model and view and in the view it self.

In dev mode, after detecting changes and updating view, Angular do a second pass and check if data binding expressions has changed during change detecting phase. If it was the case it throws an error (Expression has changed after it was checked). So, if we call a function that alter the application state in a data binding expression, Angular detect it.

So, functions with side effects, can only be used in a template statement and side effects free functions can be used both in template expressions and template statements.

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