Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Display variable inside a variable in a template

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!

like image 667
AMarquez94 Avatar asked Jan 26 '17 09:01

AMarquez94


People also ask

How do you read a template reference variable in component?

Usually, the reference variable can only be accessed inside the template. However, you can use ViewChild decorator to reference it inside your component. @ViewChild('firstNameInput') nameInputRef: ElementRef; After that, you can use this.

What template reference variable contains?

A template reference variable is often a reference to a DOM element within a template. It can also refer to a directive (which contains a component), an element, TemplateRef, or a web component.


1 Answers

{{}} 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.

like image 144
Günter Zöchbauer Avatar answered Sep 30 '22 19:09

Günter Zöchbauer