Javascript Angular 2 - 在模板中的变量内显示变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41870723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:43:22  来源:igfitidea点击:

Angular 2 - Display variable inside a variable in a template

javascripthtmlangulartypescriptbinding

提问by AMarquez94

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:

我是 Angular 2 的新手,我想在我的模板中显示一个变量中的字符串,该变量必须包含在另一个变量中。我将向您展示我的问题是什么以及我想要实现的目标的简化示例:



questionnaire.component.ts

问卷.组件.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

问卷.模板.html

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


The result I'm getting is:

我得到的结果是:

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

你好{{name}},你多大了?

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.

我试图转义存储在我的数据库中的字符串中的“{{}}”,使用 ASCII 字符而不是花括号,将它放在[innerHTML] 中......但结果总是一样的。

Do you know how can I solve this?

你知道我该如何解决这个问题吗?

Thank you very much!

非常感谢!

回答by Günter Z?chbauer

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

{{}}仅适用于 Angular 组件模板,不适用于任意字符串,也不适用于动态添加到 DOM 的 HTML。

Just change it to

只需将其更改为

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

to use TypeScript string interpolation.

使用 TypeScript 字符串插值。

回答by G.Ashok Kumar

In angular2 you have to use thiskeyword

在 angular2 中你必须使用这个关键字

For example, ${this.name}

例如,${this.name}