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

查看:189
本文介绍了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 :

我已经在我的componenet类中创建了一个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天全站免登陆