在 Angular 的 innerHTML 中使用字符串插值 [英] Using string interpolation in innerHTML in Angular
问题描述
我正在设计一款游戏,我正在动态创建内部有空格的语句,并要求玩家填写空格.我需要字符串插值来记录用户的输入,但我还需要设置动态innerHTML,因为空格可以在语句中的任何位置.
我知道这听起来很模糊,以下是相关代码示例:
app.component.html
<div class="question" [innerHTML]="questionStatement"></div>
app.component.ts
display=50;questionStatement='<div class="percent">{{display}}%</div>的美国人拥有大学学位.questionStatementExample2='加拿大是<div class="percent">{{display}}%</div>美国的大小.滑块移动(事件:任何){this.display=event.target.value;}
questionStatement
可以在句子的任何地方有
,因此需要动态入口点.
此处,字符串插值 ({{display}}
) 在 innerHTML
中不起作用.它将在屏幕上显示为 {{display}}
.在这种情况下我该怎么办?
模板文字 应该可以帮到你.如果你像下面这样修改你的组件,你的问题应该可以解决.
app.component.ts
display = 50;questionStatement = `<div class="percent">${this.display}%</div>的美国人拥有大学学位.`滑块移动(事件:任何){this.display=event.target.value;this.questionStatement = `<div class="percent">${this.display}%</div>的美国人拥有大学学位.`}
I am designing a game, and I am dynamically creating statements with blanks inside and ask the players to fill in the blanks. I need string interpolation to record user's input, but I also need to set dynamic innerHTML because the blanks can be anywhere in the statement.
I know this sounds vague, here is relevant code examples:
app.component.html
<input type="range" step="1" min="0" max="100" class="slider
(input)="sliderMoved($event)">
<div class="question" [innerHTML]="questionStatement"></div>
app.component.ts
display=50;
questionStatement='<div class="percent">{{display}}%</div>
of Americans have a university degree.'
questionStatementExample2='Canada is <div class="percent">{{display}}%</div>
the size of America.'
sliderMoved(event: any) {this.display=event.target.value;}
The questionStatement
can have <div class="percent">{{display}}%</div>
in anywhere in the sentence, hence the need of dynamic entry point.
Here, string interpolation ({{display}}
) does not work in innerHTML
. It will show up on screen literally as {{display}}
. What can I do in this case?
Template literals should help you out here. If you modify your component like below your problem should be solved.
app.component.ts
display = 50;
questionStatement = `<div class="percent">${this.display}%</div> of Americans have a university degree.`
sliderMoved(event: any) {
this.display=event.target.value;
this.questionStatement = `<div class="percent">${this.display}%</div> of Americans have a university degree.`
}
这篇关于在 Angular 的 innerHTML 中使用字符串插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!