1

Hello I am currently working with Angular/TS to dynamically render different pricing cards. I am running into many situations where I need to dynamically render text. Is it better to handle this logic directly in the html?

For example:

            <h1>
              {{ option.frequency === "YEARLY" ? ("YEARLY") : ("MONTHLY") }}
            </h1>

Or is it better to handle the logic in the component itself. Something like:

            <h1>
              {{ getFrequency(option) }}
            </h1>
R. Richards
  • 24,603
  • 10
  • 64
  • 64
Billy Keef
  • 31
  • 1
  • 7
  • I think, if its something simple like comparing/checking a variable value, use it in HTML. Like for this case you've shared. If it something complex, like filtering/mapping arrays or any other operatoin which requires other checks and all, use in ts. – amnah Aug 17 '21 at 19:20
  • 1
    It would be better to use it in template itself as it will avoid calling the getFrequency function on every change – Jameer Khan Aug 17 '21 at 19:21

2 Answers2

1

Best approach in your case is Pure Pipe. Template expression or function/getter will be triggered in any change detection cycle.

Another idea to read your code easily. For that case you should use readable names like {{ option.frequency | yearlyOrMonthly }}.

Anton Marinenko
  • 2,749
  • 1
  • 10
  • 16
0

You should use in template, if the operation is a simple one, like comparing/checking variables (as in your case). Because everytime the change-detection cycle is called it will evaluate the template and will call your function again and again. But for cases having a complex logic, use in component. Some good reads are

  1. Multiple times method calling from angular template
  2. https://medium.com/emoteev-blog/call-functions-in-angular-templates-the-good-way-f025f65b0e55
  3. https://medium.com/showpad-engineering/why-you-should-never-use-function-calls-in-angular-template-expressions-e1a50f9c0496
amnah
  • 444
  • 2
  • 6
  • Also, another good approach can be to put it like this

    {{ option?.frequency === "YEARLY" ? ("YEARLY") : ("MONTHLY") }}

    so, if option is null or undefined it wont throw exception
    – amnah Aug 17 '21 at 19:32