Angular 5 如何将字符串作为 HTML 元素插入 [英] Angular 5 How to insert a string as a HTML element

查看:31
本文介绍了Angular 5 如何将字符串作为 HTML 元素插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am getting response from server as string :

<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 表.

How can i insert this in my page directly as a html element so that i can view a html table to users.

我对下面的角度不熟悉,这是我尝试过的:

I am new to angular below is thing which i have tried :

我在我的组件类中创建了一个变量 htmltable 并尝试创建一个如下所示的 htmlelemnt

i have created a variable in my componenet class as htmltable and tried to create a htmlelemnt like below

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

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

but its not working. Please suggest me the correct way of doing this

推荐答案

在将 html 显示在模板中之前,您需要对其进行清理.

You need to sanitize your html before displaying it in the template.

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>'
    )
  }
}

现场演示

这篇关于Angular 5 如何将字符串作为 HTML 元素插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆