Angular 5如何将字符串作为HTML元素插入

时间:2018-04-14 14:15:27

标签: angular angular5

我收到来自服务器的响应字符串:

<table><thead><tr> <th scope="col">Home</th> <th scope="col">Page </th> <th scope="col">World </th> <th scope="col">HE </th> <th scope="col">MAN</th> <th scope="col">GO</th></tr></thead><tbody><tr><td>1</td><td>2</td><td>3</td><td>1</td><td>145</td><td>42</td></tr><tr><td>12</td><td>3125</td><td>315</td><td>2554</td><td>5542</td><td>331255</td></tr></tbody></table>

我如何直接在我的页面中将其作为html元素插入,以便我可以向用户查看html表。

我对角度的新手是我尝试过的东西:

我在我的componentsnet类中创建了一个变量为htmltable,并试图创建一个如下所示的htmlelemnt

this.htmltable = document.createElement(serverresponse.htmltable)

但它不起作用。

我也尝试过这种方式:

 <div class="dynamically_created_div unique_identifier" #d1></div>
    @ViewChild('d1') d1:ElementRef;
        this.renderer.appendChild(this.d1, serverresponse.htmltable);

但它不起作用。请建议我这样做的正确方法

2 个答案:

答案 0 :(得分:8)

在将html显示在模板中之前,您需要清理它。

import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  template: `
  <div [innerHtml]="safeHtml"></div>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  safeHtml: SafeHtml;

  constructor(private sanitizer: DomSanitizer) { }

  ngOnInit() {
    this.safeHtml = this.sanitizer.bypassSecurityTrustHtml(
      '<button>Click me</button>'
    )
  }
}

Live demo

答案 1 :(得分:4)

您可以使用innerHtml指令。

<div [innerHTML]="theHtmlString"></div>

在Component类

theHtmlString=  '<table><thead><tr> <th scope="col">Home</th> <th scope="col">Page </th> <th scope="col">World </th> <th scope="col">HE </th> <th scope="col">MAN</th> <th scope="col">GO</th></tr></thead><tbody><tr><td>1</td><td>2</td><td>3</td><td>1</td><td>145</td><td>42</td></tr><tr><td>12</td><td>3125</td><td>315</td><td>2554</td><td>5542</td><td>331255</td></tr></tbody></table>';