本文介绍了Angular2 *ngIf=“afunctioncall()";导致函数被调用 9 次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

@Component({选择器:'我的应用',模板:`<h1>你好</h1><div *ngIf="returnsTrue()"><h1>世界</h1>

`,})出口类应用{名称:字符串;构造函数(){this.name = 'Angular2'}返回真():布尔{console.log('返回真');返回真;}}

查看相关的 plnkr:

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

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

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

有没有办法避免它?

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

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

解决方案

我怀疑您的函数在每个变更检测周期都会被调用,尤其是在开发模式下,Angular 正在检查 *ngIf 多次更改,这样做就是调用函数.

避免这种情况的一种方法是更改​​函数中的类变量,并在 *ngIf 中监视该变量:

@Component({选择器:'我的应用',模板:`<h1>你好</h1><div *ngIf="isTrue"><h1>世界</h1>

`,})出口类应用{名称:字符串;isTrue:boolean = false;构造函数(){this.name = 'Angular2'setTimeout(() => {this.returnsTrue();}, 5000);}返回真():布尔{console.log('返回真');this.isTrue = true;}}

调整了您的 Plunker 以显示这一点.

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;
    }
}

See associated plnkr:

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

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?

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:

ng-if being called more times than it should

解决方案

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.

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;
    }
}

I adapted your Plunker to show this.

这篇关于Angular2 *ngIf=“afunctioncall()";导致函数被调用 9 次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:35