gpt4 book ai didi

Angular2 *ngIf ="afunctioncall()"导致函数被调用 9 次

转载 作者:太空狗 更新时间:2023-10-29 17:13:47 24 4
gpt4 key购买 nike

我正在使用 Angular2 并希望元素根据函数调用的结果有条件地显示。

当我这样做时,我注意到该函数被调用了多次。

@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:

http://plnkr.co/edit/MScwD3LaIj9YfBlwWltw?p=preview

'Returning true' console.log 输出了 4 次。

谁能告诉我为什么会发生这种情况?

有什么办法可以避免吗?

我看过以下帖子,但它与 Angular 1 相关,并且为 Angular2 重写了摘要周期,我不确定它是否相关:

ng-if being called more times than it should

最佳答案

我怀疑你的函数在每个变化检测周期都会被调用,特别是在开发模式下,当 Angular 多次检查 *ngIf 中的表达式是否发生变化时,这样做就是调用函数.

避免它的一种方法是更改​​函数中的类变量,并在 *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;
}
}

adapted your Plunker来展示这一点。

关于Angular2 *ngIf ="afunctioncall()"导致函数被调用 9 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39850484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com