Rahul
Rahul

Reputation: 5834

How to render angular variables using innerHTML - Angular2

In my application their is some text which is coming from a constant file which is declared like this:

  export const EmpStrings = {
    data:  "Welcome {{employee.name}}"
  }

And In my component file there is an object called employee.

   public employee = { name: 'xyz', dept: 'EE' }

Now In my HTML I want to use it like this:

<div class='e-data' [innerHTML] = "EmpStrings.data"></div>

But this didn't seems to be working. I tried various variations:

[inner-html] = "EmpStrings.data"
[innerHTML] = {{EmpStrings.data}}
[innerHTML] = "{{EmpStrings.data}}"

But none of them seems to be working.

Upvotes: 2

Views: 3476

Answers (3)

yurzui
yurzui

Reputation: 214077

If you don't want to use JitCompiler then you can parse string yourself

component.ts

ngOnInit() {
  this.html = EmpStrings.data.replace(/{{([^}}]+)?}}/g, ($1, $2) => 
      $2.split('.').reduce((p, c) => p ? p[c] : '', this));
}

template

<div [innerHTML]="html"></div>

Plunker Example

Upvotes: 3

Rex
Rex

Reputation: 678

Angular doesn't interpolate strings like this, as far as I know one of the reason is security. The const doesn't have the context where your employee is in hence you see the error saying employee is not defined.

You could do this:

Change your constant:

export const EmpStrings = {data:  "Welcome "};

then:

<div class='e-data'>{{EmpStrings.data}}{{employee.name}}</div>

But if for some reason you must use [innerHTML]:

  1. In your component class, add a method:

    getWelcomeMessage(){return EmpStrings.data + this.employee.name;}

  2. in the component view:

    <div class='e-data' [innerHTML] = "getWelcomeMessage()"></div>

Upvotes: 0

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41437

use ${employee.name} to bind angular variable to innerHTML

"data": `Welcome ${employee.name}`

Upvotes: 2

Related Questions