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

时间:2019-09-18 19:20:40

标签: angular angular7 angular8

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

{"result" => "HTML code"}

如何解析HTML代码并从此响应中获取表格?

我试图将这段代码放在页面上的隐藏块中:

<div #content>HTML code here from response</div>

接下来呢?如何解析?

2 个答案:

答案 0 :(得分:2)

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

我们应该始终对内容进行修饰,以防止DOMSanitizer进行任何恶意活动。因此,我们可以如上所述创建管道,并在应用程序中的任何位置使用它。

答案 1 :(得分:2)

app.component.ts

open(CERT_FILE, "wt").write(
    crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode())
open(KEY_FILE, "wt").write(
    crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode())

app.component.html

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>`
}