How to render angular variables using innerHTML - Angular2

南楼画角 提交于 2021-01-28 05:19:01

问题


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.


回答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




回答2:


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

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



回答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:

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>



来源:https://stackoverflow.com/questions/45234240/how-to-render-angular-variables-using-innerhtml-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!