Home > Mobile >  Avoid duplicating *ngIf Angular 2
Avoid duplicating *ngIf Angular 2

Time:05-05

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?

CodePudding user response:

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 pipes.

CodePudding user response:

Contrary to popular belief it's not "wrong" to call functions in your HTML.

What's wront is calling them too frequently, and making them do too much things.

If you have a function that only creates a string, that's more than okay, for instance

greet(name: string) { return 'Hello '   name; }

But if your function have thousands of instructions, yeah, that's going to be an issue ...

Second point, the frequency of the calls : Angular operates some magic to detect changes, which you can disable with something called ChangeDetectionStrategy. If you do that, Angular triggers change detection only on specific conditions, making your UI update less often, thus consuming less resources.

With this, you can even call complex functions in your HTML (that's obviously depending on the function and how often the detection triggers).

  • Related