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

1

2 Answers 2

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

2 Comments

The variable sampleData is dynamic and will be stored in a separate json. Hence i need to compile it in html instead of direct data interpolation.
@GaneshBabu you can complile your string as required in ngOnInit()
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

1 Comment

We need "<div> This is my variable <strong>{{ item }}</strong> which is dynmically parsed. </div>" to be stored in a variable inside component. The above solution doesn't work for that case

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.