Search code examples
htmlangularconditional-operator

Angular: Using the ternary operator in html template


The a simple ternary operator can be used like this within html:

<div> {{ showStringOneFlag ? 'Display String 1' : 'Display String 2' }} </div>

This may be more convenient than setting a string variable 20 times in javascript.

My question is if the ternary operator is too expensive to be executed each digest cycle? Should this function be avoided or used sparingly? Is its footprint minimal on the digest cycle and there is no need to worry about it? Everywhere I look for an answer I see that it is comparable to an if/else statement in terms of speed, but in html there isn't really an equivalent to an if/else statement.


Solution

  • 1) Is the ternary operator too expensive to be executed each digest cycle?

    The ternary operator itself should not be to expensive to be executed at each digest cycle. A ternary operator should evaluate in the region of microseconds. With that said, if you call a function that evaluates to a truthy/falsy or if your ternary operator itself calls a function, then it could take upwards of milliseconds depending on how expensive your function is.

    2) Should this function be avoided or used sparingly?

    If they are clean ternary operators, i.e. make explicit comparisons without function calls, then you should be able to use as many as you like, there should be no significant impact.

    3) Everywhere I look for an answer I see that it is comparable to an if/else statement in terms of speed, but in html there isn't really an equivalent to an if/else statement.

    Angular Interpolation is Javascript, not HTML.

    So if you want to look at a comparison, you can look at the performance difference between a ternary operator and an if-statement in pure JS. However, I'm sure the performance difference should be negligble.

    Further Reading to help understand how Angular interprets and processes HTML.