Home > Blockchain >  Angular template conditions performance
Angular template conditions performance

Time:12-13

I am using the latest angular and recently has some doubt related to template conditions and performances. I know that calling method in template is bad practice and it is called every change detection cycle but I am not sure for the other 2 solution.

 1) <div *ngIf="isConditionsTrue"></div>
 2) <div *ngIf="isConditionsTrueFunction()"></div>
 3) <div *ngIf="condition1 || condition2 && !condition3"></div>

And in the ts file:

ngOnInit(): void {
   this.isConditionsTrue = this.condition1 || this.condition2 && !this.condition3;
}

isConditionsTrueFunction(): boolean {
   return this.condition1 || this.condition2 && !this.condition3;
}

What is the best options in we talked about:

a) Readability . I guess 1 is the winner.

b) Performance I am curious between 2 and 3. Does angular has some caching mechanism like in pure pipes and does not calculate conditions in template every time, or 2 and 3 are the same ?

c) Architecture I know that 2 is bad practice. Does the 3 consider as bad practice since we use expression in the component template ?

CodePudding user response:

there is no official angular documentation for "I know that 2 is bad practice" I would love to see someone prove this wrong!!!

Reasoning:

Never use array method or heavy computation methods even if its inline or inside a function. A few examples are the array methods, find, some, filter, etc. NgIf methods should always be very basic (just simple variable AND OR checks), because they are triggered everytime the change detection runs

When the conditions are too large (like 5 and conditions chained together) go for a function (in terms of readability and for Unit testing as well as documentation)

When the conditions are simple use the condition inline in HTML, since its a waste to write a separate function for it!

CodePudding user response:

I think it`s OK to call methods in template if you use ChangeDetection.OnPush

  • Related