1

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?

1 Answer 1

3

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.`
}
Sign up to request clarification or add additional context in comments.

5 Comments

Also just to add a small note: To make sure that the class also gets applied, I need to add: encapsulation: ViewEncapsulation.none to app.component.ts
Hi, I tried this method and it works only if I type the literal string word by word inside the sliderMoved method, e.g.: this.questionStatement='<div class="percent">${this.display}%</div> of Americans have a university degree.' . It does not work when I use a variable to replace the literal string, for instance, var replacement='<div class="percent">${this.display}%</div> of Americans have a university degree.'; this.questionStatement=this.replacement;does not work (it still shows the same number as it was first defined). Any idea how to work around it?
Cool, let me know if you face issue.
@PalSingh sir i have returned innerHTML with Template expression but i got returned same ${this.tenantName} string instead of value.can you please help me on that how to get value ?
@KapilSoni Maybe your issue us solved. If not, please share a code sample of your issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.