2

I need to achieve dynamic variable compilation inside HTML Template using Angular 7.

Here is my sample code:

app.component.ts:

username = 'User Name';
sampleData = "This is my <strong>{{username}}</strong>";

app.component.html:

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

But, still the output is

This is my {{username}}.

My Expected output is,

This is my UserName

The same feature can be achieved in Angular 1 using $compile. Please let me know how to achieve this in Angular 7

Ganesh Babu
  • 3,590
  • 11
  • 34
  • 67

2 Answers2

1

Try this:

username = 'User Name';
sampleData = "This is my <strong>" + this.username + "</strong>";

As per your comment, for dynamic tdata you can do this:

username = 'User Name';
sampleData = "This is my {{username}}";

ngOnInit() {
   this.sampleData = this.sampleData.replace("{{username}}", `<strong> ${this.username} </strong>`)
}
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
0

You can use ng-template and create a local reference of it and use it with ngTemplateOutlet wherein you can pass in the dynamic content.

HTML (template)


<ng-template #temp let-item>
  <div> This is my variable <strong>{{ item }}</strong> which is dynmically parsed. </div>
</ng-template>

<ng-container *ngTemplateOutlet="temp; context: { $implicit: name }"></ng-container>

Typescript

export class AppComponent  {
  name = 'Angular';
}

Check the stackblitz demo - https://stackblitz.com/edit/angular-lec12u

Gopal Yadav
  • 368
  • 2
  • 8
  • We need "
    This is my variable {{ item }} which is dynmically parsed.
    " to be stored in a variable inside component. The above solution doesn't work for that case
    – Ganesh Babu Aug 01 '19 at 07:44