fenix2222
fenix2222

Reputation: 4730

Is it bad to bind to properties/functions vs variables in Angular 4+?

I am trying to understand if it is a bad practice to bind to functions in angular templates vs binding to variables/expressions. Does it make any difference?

For example:

Option 1

<span *ngIf="!!myForm.value && !!myform.errors && !!myForm.errors['required']" ...

versus

Option 2

HTML
<span *ngIf="requiredError" ...

TS
get requireError() {
    return !!this.myForm.value && !!this.myform.errors && !!this.myForm.errors['required'];
}

As far as I understand there is no difference, both expression will keep getting executed, in which case I would always go for Option 2. However, I keep getting told that property/function binding is bad as angular adds a watcher and function keeps getting executed all the time. My understanding is that it will also be the case for Option 1. I would really appreciate some articles or links to documentation describing this, can't find much online.

Specifically, when using valid, touched, dirty (which are already get properties in angular), I don't see how it would be different unless angular somehow magically handles those differently.

I see style guide has a brief mention of this: https://angular.io/guide/styleguide#put-presentation-logic-in-the-component-class

Upvotes: 4

Views: 2679

Answers (1)

bertrandg
bertrandg

Reputation: 3207

To answer you globally, in Angular, you have template expressions that are evaluated at each change detection run (to compare current value with new one and know if DOM need to be updated).

Examples:

<span *ngIf="expression"></span>
<div>{{ expression }}</div>
<div [class.myclass]="expression"></div>

Your expressions can contains variables or function calls, it doesn't makes any difference for angular about call frequency or performance:

myBoolean1 = true;
myBoolean2 = false;
<span *ngIf="myBoolean1 && !myBoolean2"></span>

is the same as:

myBoolean1 = true;
myBoolean2 = false;

getValue(): boolean {
    return this.myBoolean1 && !this.myBoolean2;
}
<span *ngIf="getValue()"></span>

(When and why change detection runs occurs is another subject)

BUT it's considered as a bad practise to use function calls in template because, generally, when a team is working on a codebase, people are tempted to add more and more computations in these functions which progressively leads to global performance issues.

Upvotes: 5

Related Questions