使用模板插值多次调用函数? [英] Function is getting called many times by using template interpolation?

查看:29
本文介绍了使用模板插值多次调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于基本问题,我正在尝试使用基本示例来理解 angular2 流程.

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")
    }
}

运行此示例后,演示文本"在控制台中可见 4 次,为什么会这样?谢谢.

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

推荐答案

不鼓励绑定到模板中的函数或方法,因为每次运行更改检测时都会调用这些函数.

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.

这篇关于使用模板插值多次调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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