0

I'm trying to do string interpolation in code using Angular, Typescript, HTML, etc... For some reason the 'dollar sign' appears as a string literal in the output. Can anyone help?

I need the output to as follows:

"Hello World."

Instead, I'm getting this:

"Hello ${name}."

Link: https://stackblitz.com/edit/angular-template-string-interpolation

Thanks.

Stout
  • 463
  • 8
  • 19
  • I'd strongly recommend reading https://angular.io/guide/template-syntax, or even just starting with https://angular.io/tutorial – jonrsharpe Dec 02 '19 at 20:43
  • 1
    @bela: Yes, that is the correct answer. I had tried it with the wrong characters before. That's why it failed. – Stout Dec 02 '19 at 21:06
  • @jon: Thank you. Those links are very informative. I'll give them a thorough read. – Stout Dec 02 '19 at 21:07

3 Answers3

6

To interpolate strings, you need to use template literals

Template literals use ``` (backtick) and not ' (single quote)

Also, name is a class property, so you should reference it by using this

So, your code becomes:

title: string = `Hello ${this.name}.`;
  • 1
    I had the single quote character, and it should have been the backtick character. Thank you for the help. – Stout Dec 02 '19 at 21:04
3

String interpolation only happens inside back ticks.

"Hello ${name}."

produces Hello ${name}. but

`Hello ${name}.`

produces Hello previewFrame in your example. This is because you are referencing the wrong variable. Instead of ${name} use ${this.name} otherwise you're getting the name of the frame that stackblitz renders your output in.

For the record, this is not a typescript or Angular feature. String interpolation is a newer vanilla javascript feature. More info here.

Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188
2

You need to use the this keyword and the back ticks. Like this:

title: string = `Hello ${this.name}.`;
  • I had the single quote character, and it should have been the backtick character. Thank you for the help. – Stout Dec 02 '19 at 21:05