如何从Angular中的响应解析HTML?

如何从Angular中的响应解析HTML?,angular,angular7,angular8,Angular,Angular7,Angular8,我确实请求服务器并获得JSON结果: {"result" => "HTML code"} 如何解析HTML代码并从该响应中获取表 我试图将此代码放置到页面上的隐藏块: <div #content>HTML code here from response</div> HTML代码来自响应 接下来呢?如何解析?从“@angular/core”导入{Pipe,PipeTransform}; import { Pipe, PipeTransform } from "@

我确实请求服务器并获得JSON结果:

{"result" => "HTML code"}
如何解析HTML代码并从该响应中获取表

我试图将此代码放置到页面上的隐藏块:

<div #content>HTML code here from response</div>
HTML代码来自响应
接下来呢?如何解析?

从“@angular/core”导入{Pipe,PipeTransform};
import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer } from "@angular/platform-browser";

@Pipe({name: 'sanitizeHtml'})
export class SafeHtmlPipe implements PipeTransform {
   constructor(private sanitized: DomSanitizer) {
   }
   transform(value: string) {
     return this.sanitized.bypassSecurityTrustHtml(value);
   }
}

Usage:
<div [innerHTML]="content | sanitizeHtml"></div> //Content is what you got from json
从“@angular/platform browser”导入{domsanizer}”; @管道({name:'sanitizeHtml'}) 导出类SafeHtmlPipe实现PipeTransform{ 构造器(专用消毒:DOMSanizizer){ } 转换(值:字符串){ 返回此.sanitized.bypassSecurityTrustHtml(值); } } 用法: //内容是您从json获得的内容

我们应该始终对内容进行santize,以防止使用DOMSanitizer进行任何恶意活动。因此,我们可以如上所述创建一个管道,并在app.component.ts中的任何位置使用它。

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 5';
  demo: string = `<div>
 <p>I am Yogesh</p>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
  </div>`
}
从'@angular/core'导入{Component};
@组成部分({
选择器:“我的应用程序”,
templateUrl:“./app.component.html”,
样式URL:['./app.component.css']
})
导出类AppComponent{
名称='5';
演示:字符串=`
我是约格什

我的第一个标题 我的第一段

` }
app.component.html

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


使用
innerHtml
属性您发布的div可能重复的可能的副本期望文本不是HTMLI建议谨慎使用
innerHtml
,因为它会创建内存leaks@JosephBriggs你能说什么是替代方案,这样它会更有用一点吗?谢谢