Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 396
rhavelka Avatar asked Aug 27 '26 16:08

rhavelka


2 Answers

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.

  • Architecture Overview
  • Template Syntax
  • Angular Interpolation
like image 55
Dane Brouwer Avatar answered Aug 30 '26 05:08

Dane Brouwer


Short answer is it depends on what you are rendering conditionally, and if it makes sense to use a ternary.

For simple conditional rendering, sure, a ternary is fine and will not affect performance in a noticeable manner.

However, if you are rendering giant chunks of code conditionally, or performing several/complex computations at several points in your code to determine what is rendered, it may be wiser to perform this step outside of the HTML.

For more information see this SO link

like image 28
RGordon Avatar answered Aug 30 '26 06:08

RGordon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!