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
source share