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

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

问题描述

很抱歉出现基本问题,我试图通过基本示例来了解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天全站免登陆