2

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.

The Hungry Dictator
  • 3,444
  • 5
  • 37
  • 53
Rahul
  • 5,594
  • 7
  • 38
  • 92
  • @Vega yes I already tried all the possible ways listed there. – Rahul Jul 21 '17 at 09:39
  • You need to use `JitCompiler` if you want to have binding within string. For example https://stackoverflow.com/questions/39410355/how-to-use-variable-to-define-templateurl-in-angular2 or https://stackoverflow.com/questions/40060498/angular-2-1-0-create-child-component-on-the-fly-dynamically/40080290#40080290 – yurzui Jul 21 '17 at 09:40

3 Answers3

3

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

yurzui
  • 205,937
  • 32
  • 433
  • 399
2

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

"data": `Welcome ${employee.name}`
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
0

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>

Rex
  • 658
  • 4
  • 10