使用模板插值多次调用函数?
Function is getting called many times by using template interpolation?
对于基本问题,我很抱歉,我正在尝试使用基本示例来理解 angular2 流程。
import { Component } from '@angular/core';
@Component({
selector:'my-app',
template:'Test {{ getVal() }}'
})
export class AppComponent{
getVal():void{
console.log("demo text")
}
}
在运行这个例子之后,"demo text"在控制台中出现了4次,为什么会这样?谢谢
不鼓励绑定到模板中的函数或方法,因为每次更改检测时都会调用这些函数 运行。
您至少应该在函数内部缓存结果,以避免重复重新计算潜在的昂贵计算。
更好的方法是在结果依赖的属性发生变化时重新计算结果,并将结果分配给 属性 并从视图绑定到此 属性。
对于基本问题,我很抱歉,我正在尝试使用基本示例来理解 angular2 流程。
import { Component } from '@angular/core';
@Component({
selector:'my-app',
template:'Test {{ getVal() }}'
})
export class AppComponent{
getVal():void{
console.log("demo text")
}
}
在运行这个例子之后,"demo text"在控制台中出现了4次,为什么会这样?谢谢
不鼓励绑定到模板中的函数或方法,因为每次更改检测时都会调用这些函数 运行。
您至少应该在函数内部缓存结果,以避免重复重新计算潜在的昂贵计算。
更好的方法是在结果依赖的属性发生变化时重新计算结果,并将结果分配给 属性 并从视图绑定到此 属性。