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: