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

Sam*_*amF 8 angular2-template angular

我正在使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

请参阅相关的plnkr:

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

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

谁能指出我为什么会这样?

无论如何要避免它吗?

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

ng-if被调用的次数超过它应该的次数

Har*_*rry 10

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

避免它的一种方法是更改​​函数中的类变量,并在以下内容中监视该变量*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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我改编了你的Plunker来展示这一点.