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.

2

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to do this more generically through one of Angular's existing constructs, like a directive or pipe?
2

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

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

6 Comments

If I use ${employee.name} then I am getting error message that emloyee is not defined in constant file
post the employee object
use this.employee.name
why are you trying to add angular variable to constant
I need parse some long strings and then add some content via vairables. And in constant file I have declared this like: message: "Hello mr. employee.name" And then any controller which wants to use can use it via message.
|
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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.