Home > front end >  Using getters vs using long set of variables
Using getters vs using long set of variables

Time:11-25

In a component I have some ngIf and ngClass conditions which use more than 5 or 6 variables and some are even used multiple times across. Is it better to use a getter for this long set of variables than using it directly in the template and are there any issues regarding Change Detection while using getter instead of variables directly.

Can I safely and efficiently use the getter or is there something else with which I can keep my HTML clean and readable?

Sample code:

HTML

<div [class.random]="a && b || (c && !d) || (a && !e)">
 <span *ngIf="a && b || (c && !d) || (a && !e)">
  Something so random
 </span>
</div

vs

HTML

<div [class.random]="myCondition">
 <span *ngIf="myCondition">
  Something so random
 </span>
</div>

TS

get myCondition(): boolean {
 return a && b || (c && !d) || (a && !e);
}

CodePudding user response:

There are no problems to use getters or function inside your template. But you need to make sure that you have the correct ChangeDetectionStrategy in order to avoid multiple executions. Try read this article: link

CodePudding user response:

As a rule of thumb, you should always keep your business logic in your component /ts/ instead of the markup /html/. This will help you later on catch up what is going on, especially if you have descriptive names for your functions.

I think there is not much difference as of speed, maybe that you will not need that much public variable, which makes your code more robust and safe. And that makes your HTML more easy to read. This is definitely a good point.

You can use [ngClass]: {'random': myCondition} as well here.

Of course with this, you have to take care of how many times your function is executed, but that now really depends on your other logic and you ChangeDetectionStrategy.

  • Related