Angular 2 - Display a variable inside a variable in a template

I am completely new in Angular 2, and I want to show in my template a string in a variable that should 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> 

As a result, I get:

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

and my desired result:

Hi Albert, how old are you?

I tried to escape from "{{}}" in a string stored in my database, instead of using curly braces I used the ASCII character, placed it inside [innerHTML] ... but the result was always the same.

Do you know how I can solve this?

Many thanks!

+7
javascript html angular typescript binding
source share
2 answers

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

Just change it to

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

to use TypeScript string interpolation.

+13
source share

In angular2 you need to use this keyword

For example, $ {this.name}

+1
source share

All Articles