Angular 2 - Display variable inside a variable in a template

32,248

{{}} only works in Angular component templates and not in arbitrary strings and also not in HTML added dynamically to the DOM.

Just change it to

 question.title = `Hello ${this.name}, how old are you?`;

to use TypeScript string interpolation.

Share:
32,248
AMarquez94
Author by

AMarquez94

Young programmer that just finished Computer Engineering Degree at University. Passionated about technology and video games. Real world problems, here I go!

Updated on July 05, 2022

Comments

  • AMarquez94
    AMarquez94 almost 2 years

    I'm quite new in Angular 2, and I want to show in my template a string in a variable that has to contain inside another variable. I will show you a simplified example of what my problem is and what I want to achieve:


    questionnaire.component.ts

    /* Starts being "", populating an input text will modify this */
    name = "Albert";
    
    /* This variable comes from calling an API, here I just put it as created to simplify */
    question.title = "Hello {{name}}, how old are you?";
    

    questionnaire.template.html

    <p>{{question.title}}</p>
    

    The result I'm getting is:

    Hello {{name}}, how old are you?

    and my desired result would be:

    Hello Albert, how old are you?

    I have tried to escape the "{{ }}" in the string stored on my DB, used the ASCII character instead of the curly braces, put it inside [innerHTML]... but the result was always the same.

    Do you know how can I solve this?

    Thank you very much!

  • AMarquez94
    AMarquez94 over 7 years
    Thanks! It worked like a charm. I guess it will also work if I get the object "question" from DB calling an API directly if the "title" field is Hello ${this.name}..., won't it?
  • Günter Zöchbauer
    Günter Zöchbauer over 7 years
    Sorry, I don't know what that means exactly. It depends on where you put your code and if this.name is available from where the code is executed, but in principle this works everywhere in TS code.
  • AMarquez94
    AMarquez94 over 7 years
    Ok, don't worry, will try to try it myself and see if it works in my particular case. Thank you very much again!
  • Ryan Coolwebs
    Ryan Coolwebs almost 5 years
    Thanks for this solution, Initially was not working for me but that was because I was using single quotes and not backticks!