Home > database >  Nested text interpolation in Angular 12: binding a string with nested curly braces
Nested text interpolation in Angular 12: binding a string with nested curly braces

Time:11-09

I have these variables in my component:

name = 'Steven';
greeting = 'Hi, {{name}}!';

and in my template:

<div [innerHtml]="greeting"></div>

This outputs Hi, {{name}}! but I want it to render Hi, Steven!. How can I do this?

This is a simplified example to show the issue I have. In reality, our current system allows messages with one or more component variables.

I'm using Angular 12.

CodePudding user response:

In your ts file you cannot use Angular template string interpolation. Instead you should use the JS/TS string interpolation, ${expresssion} with a JS/TS getter method.

name = 'Steven';

get greeting(): string {
  return `Hi, ${this.name}!`;
} ;

And your html

<div [innerHtml]="greeting"></div>

This will allow you to build the greeting dynamically based on the current value of name. If name changes, the greeting updates.

See stackblitz link below

https://stackblitz.com/edit/angular-ivy-2kq5vb

CodePudding user response:

if you are using property binding then you have to do something like

<div [innerHtml]="'Hi, '   name   '!'"></div>

if you remove the property binding then you can do something like this:

<div innerHtml="Hi, {{name}}!"></div>
  • Related