Is it a good practice to use Function calls inside {{}} (Curly Brackets)?

  • A+
Category:Languages

Is it a good practice to use Function calls inside {{}} (Curly Brackets)?

Is there any way to do this? within the component, for example (maybe using ngOnChanges or anything like that...)

Template

<div class="container">     {{ bootstrap() }}     {{ validate() }}       <textarea class="form-control">{{ fullHtml }}</textarea>     <button (click)="copy()" class="btn btn-primary">Click to Copy HTML</button>     <textarea class="form-control">{{ validator }}</textarea>     <button (click)="copy()" class="btn btn-warning">Click to Copy Validate</button>      <button class="btn btn-danger" (click)="add()">Add page and input</button> </div> 

Component

class HomeComponent {     fullHtml = "";     validator = "";     pages = [{         "name": "Page 1"     },{         "name": "Page 2"     }];      inputs = [{         "name": "input_1",         "required": true     },{         "name": "input_2",         "required": false     }];      public bootstrap() {         this.fullHtml = this.pages.map((page, pageNumber) => {             return '<div class="row">' +                 page.name +                 '</div>'         }).join('')     }      public validate(){         this.validator = this.inputs.map((input, i) => {             return '"' + input.name + '" => [' + (input.required? 'required': 'nullable') + '],/n';         }).join('')     }      public copy(){         alert("under construction");     }      public add(){         this.pages.push({             name: "page 3"         });         this.inputs.push({             "name": "input_3",             "required": true         });     } } 

https://jsfiddle.net/1hk7knwq/10283/

ps. I need to display HTML content in a textarea, that's why I'm doing the html inside the component.

 


The answer for your question is: it depends.

If the execution time of the function is short, that's fine. In case the function includes many complex calculation which take a quite long time to finish, then it might cause a serious problem with user experience.

This is what the Angular team said in their official document:

Quick execution

Angular executes template expressions after every change detection cycle. Change detection cycles are triggered by many asynchronous activities such as promise resolutions, http results, timer events, keypresses and mouse moves.

Expressions should finish quickly or the user experience may drag, especially on slower devices. Consider caching values when their computation is expensive.

For more information, you could read it at: https://angular.io/guide/template-syntax#quick-execution

Hopefully, that helps.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: