首页 > 解决方案 > how to convert a variable into HTML element with Angular

问题描述

I've a json file

{
  "articles": [
    {
      "id": 1,
      "title": "<h1>How to install Atom</h1>"
    },
    {
      "id": 2,
      "title": "<h1>Installing Boostrap</h1>"
    }
  ]
}

I am using json-server with angular 8 to read this json. As you can see title field is supposed to be an html head tag when rendered on screen. But it is getting printed as it is. See, this is what I am trying to say. this. I want to convert this into heading-1 tag in run time. My app.component.html is

  <div id="data-container">    
  </div>

  Hello
  <table>
    <tr *ngFor="let art of lstcomments">
      <td>{{art.id}}</td>
      <td>
        document.querySelector('#data-container').innerHTML={{art.title}}
      </td>
    </tr>
  </table>
</div>
<router-outlet></router-outlet>

My title is stored in {{ art.title }}. I tried creating a separate div with id data-container and used document.querySelector but the whole code gets printed as a string. What should I do now.

标签: javascriptangular

解决方案


As mentionend in the official docs, Angular automatically sanitize HTML so you can't just put it in the template with a variabile. This is done to prevent different kind of attacks by allowing external actors to interact with your page and push content in your HTML.

For the HTML to be interpreted, you can bind it to the HTML property innerHTML as in this example:

<span [innerHTML]="art.title"></span>


推荐阅读