【问题标题】:Angular 5 How to insert a string as a HTML elementAngular 5 如何将字符串作为 HTML 元素插入
【发布时间】:2018-09-24 17:17:14
【问题描述】:

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

<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 表格。

我是 Angular 的新手,下面是我尝试过的东西:

我在我的组件类中创建了一个变量作为 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);

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

【问题讨论】:

标签: angular angular5


【解决方案1】:

在模板中显示之前,您需要对 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

【讨论】:

  • 这是正确的解决方案,适用于所有 HTML 元素,包括样式标签,对于注入元素非常有用
  • "调用任何 bypassSecurityTrust... API 会禁用 Angular 的内置清理" , "警告:使用不受信任的用户数据调用此方法会使您的应用程序面临 XSS 安全风险!"来源:angular.io/api/platform-browser/DomSanitizer.
【解决方案2】:

您可以使用innerHtml 指令。

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

在组件类中

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>'; 

【讨论】:

  • 这行不通。 Angular 会以这种方式清理所有的 innerHtml 集。
  • @TomaszKula - 它应该可以工作。您所说的对于插值是正确的,但在绑定innerHTML 时则不然。见this stackblitz
猜你喜欢
  • 1970-01-01
  • 2015-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-08
  • 1970-01-01
相关资源
最近更新 更多