Search code examples
angularangular2-template

Avoid duplicating *ngIf Angular 2


Calling functions inside the template causes infinite calls

<div>{{ renderHtml() }}</div>

The same behavior depicts inside *ngIf expression

While the template has multiple expressions, writing duplicating *ngIf expression inside the template doesn't fit DRY principle

In some angular projects, I have met get method calls in .ts

*ngIf="dryState"

get dryState() {return boolean }

Are getters a proper way to avoid *ngIf duplication? Or the only correct way is to use pipes?


Solution

  • Getters in a template behave exactly the same as functions in a template, they get called with every change detection. You can easily see this yourself if you put some console.log in the getter. So better use properties or pure pipes.