Angular2 * ngIf = "afunctioncall ()" causes the function to be called 9 times

I work with Angular2 and want the element to be conditionally displayed based on the result of the function call.

When I do this, I notice that the function is called several 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 related plnkr:

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

"Return true" console.log is displayed 4 times.

Can someone tell me why this is happening?

And still avoid it?

I saw the next post, but with Angular 1 associated with it, and the digest cycle was being rewritten for Angular2. I am not sure if this is important:

ng - if called more than once

+5
source share
1 answer

I suspect that your function is called for every change detection cycle, especially in dev mode, when Angular checks the *ngIf for changes several times and calls the function.

One way to avoid this is to change the class variable in your function and control this variable in *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.

+5
source

Source: https://habr.com/ru/post/1257684/


All Articles