Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Templates - inline expressions vs calling to function

Is there any difference between those two:

<li [ngClass]="{disabledField: condition1 && condition2 && condition3}">Click</li>

vs

<li [ngClass]="{disabledField: shouldDisableField()}">Click</li>

and in component class:

shouldDisableField(): boolean{
  return this.condition1 && this.condition2 && this.condition3;
}
like image 418
Ben Avatar asked Jan 03 '18 13:01

Ben


2 Answers

Most answers here only mention the difference in performance as marginal. I don't think this is correct and the performance here can be quiet significant. Please refer to Phil Parsons great article about this: Function calls in Angular expressions are killing your apps performance

You should be aware of the performance hit as shown there

like image 64
Ziv Glazer Avatar answered Oct 17 '22 20:10

Ziv Glazer


The only difference is between a function call and evaluating an expression in JavaScript, Angular is irrelevant here. Function call is usually marginally slower, so the first option should be marginally faster.

Angular view compiler produces the following code for updateRenderer function:

function(_ck, _v) {
    var _co = _v.component;
---> var currVal_0 = _ck(_v, 3, 0, ((_co.condition1 && _co.condition2) && _co.condition3));
    _ck(_v, 2, 0, currVal_0);
}

And

function(_ck, _v) {
    var _co = _v.component;
--> var currVal_0 = _ck(_v, 3, 0, _co.shouldDisableField());
    _ck(_v, 2, 0, currVal_0);
}

As you can see only one line is different and that is all that matters.

You can read more about updateRenderer function in the article:

  • The mechanics of DOM updates in Angular.
like image 37
Max Koretskyi Avatar answered Oct 17 '22 21:10

Max Koretskyi