【问题标题】:Using string interpolation in innerHTML in Angular在 Angular 的 innerHTML 中使用字符串插值
【发布时间】:2018-12-18 22:03:30
【问题描述】:

我正在设计一款游戏,我正在动态创建带有空格的语句,并要求玩家填写空格。我需要字符串插值来记录用户的输入,但我还需要设置动态 innerHTML,因为空格可以在语句中的任何位置。

我知道这听起来很模糊,这里是相关的代码示例:

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;}  

questionStatement 可以在句子的任何位置有&lt;div class="percent"&gt;{{display}}%&lt;/div&gt;,因此需要动态入口点。

这里,字符串插值 ({{display}}) 在 innerHTML 中不起作用。它将在屏幕上显示为{{display}}。在这种情况下我该怎么办?

【问题讨论】:

    标签: javascript html css angular typescript


    【解决方案1】:

    Template literals 应该可以帮到你。如果你像下面这样修改你的组件,你的问题应该得到解决。

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

    【讨论】:

    • 还只是添加一个小注释:为了确保该类也被应用,我需要添加:encapsulation: ViewEncapsulation.none to app.component.ts
    • 嗨,我试过这个方法,只有当我在 sliderMoved 方法中逐字输入文字字符串时它才有效,例如:this.questionStatement='&lt;div class="percent"&gt;${this.display}%&lt;/div&gt; of Americans have a university degree.'。当我使用变量替换文字字符串时它不起作用,例如,var replacement='&lt;div class="percent"&gt;${this.display}%&lt;/div&gt; of Americans have a university degree.'; this.questionStatement=this.replacement;不起作用(它仍然显示与第一次定义相同的数字)。知道如何解决它吗?
    • 酷,如果您遇到问题,请告诉我。
    猜你喜欢
    • 2017-08-04
    • 2023-03-17
    • 2023-02-20
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 2018-07-26
    相关资源
    最近更新 更多