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

Angular2 *ngIf="afunctioncall()" results in the function being called 9 times

我正在使用 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次

谁能告诉我为什么会这样?

有没有办法避免它?

我看到了以下 post 但是它与 Angular 1 相关并且摘要周期正在为 Angular2 重写 我不确定它是否相关:

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

避免它的一种方法是更改​​函数中的 class 变量,并在 *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来展示这个。