Function is getting called many times by using template interpolation?

无人久伴 提交于 2019-12-17 16:31:44

问题


Sorry for basic question, I am trying to understand the angular2 flow using basic example.

import { Component } from '@angular/core';

@Component({
    selector:'my-app',
    template:'Test {{ getVal() }}'
})

export class AppComponent{ 
    getVal():void{
        console.log("demo text")
    }
}

After running this example, "demo text" is visible in console 4times, why is it so ? Thanks.


回答1:


Binding to functions or methods in the template is discouraged because these functions are called every time change detection is run.

You should at least cache results inside the function to avoid repeatedly recalculating potential expensive calculations.

A better approach is to recalculate the result when properties change the result depends on, and assign the result to a property and bind to this property from the view instead.



来源:https://stackoverflow.com/questions/40080541/function-is-getting-called-many-times-by-using-template-interpolation

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