Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

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

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

Solution 3:

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:

exportconst EmpStrings = {data:  "Welcome "};

then:

<divclass='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>

Post a Comment for "How To Render Angular Variables Using Innerhtml - Angular2"