Angular2 * ngIf ="afunctioncall()".导致该函数被调用9次 [英] Angular2 *ngIf="afunctioncall()" results in the function being called 9 times
问题描述
我正在使用Angular2,希望一个元素根据函数调用的结果有条件地显示.
I am working with Angular2 and want an element to conditionally display based upon the result of a function call.
当我这样做时,我注意到该函数被多次调用.
When I do this I've noticed that the function is called multiple times.
@Component({
selector: 'my-app',
template: `
<h1>Hello</h1>
<div *ngIf="returnsTrue()">
<h1>World</h1>
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = 'Angular2'
}
returnsTrue(): boolean {
console.log('Returning true');
return true;
}
}
请参阅关联的plnkr:
See associated plnkr:
http://plnkr.co/edit/MScwD3LaIj9YfBlwWltw?p=preview
"Returning true" console.log输出4次.
The 'Returning true' console.log is output 4 times.
有人能指点我为什么发生这种情况吗?
Can anyone point me as to why this occurs?
还有反正可以避免它吗?
And is there anyway to avoid it?
我看过以下帖子,但是它与Angular 1相关,并且摘要周期已为Angular2重写,我不确定是否相关:
I've seen the following post however with it being related to Angular 1 and the digest cycle being re-written for Angular2 I'm not sure it's relevant:
推荐答案
我怀疑您的函数在每个更改检测周期都被调用,尤其是在开发模式下,当Angular在*ngIf
中的表达式多次检查更改时,这样做就是在调用函数.
I suspect that your function is called on every change detection cycle, particularly in dev mode when Angular is checking the expression in the *ngIf
for changes multiple times, and in doing so is calling the function.
避免这种情况的一种方法是更改函数中的类变量,并在*ngIf
中监视该变量:
One way to avoid it would be to change a class variable in your function, and monitor that variable in your *ngIf
:
@Component({
selector: 'my-app',
template: `
<h1>Hello</h1>
<div *ngIf="isTrue">
<h1>World</h1>
</div>
`,
})
export class App {
name:string;
isTrue:boolean = false;
constructor() {
this.name = 'Angular2'
setTimeout(() => {
this.returnsTrue();
}, 5000);
}
returnsTrue(): boolean {
console.log('Returning true');
this.isTrue = true;
}
}
我调整了柱塞的位置进行了显示.
这篇关于Angular2 * ngIf ="afunctioncall()".导致该函数被调用9次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!