【问题标题】:How to parse HTML from response in Angular?如何从Angular中的响应中解析HTML?
【发布时间】:2020-01-19 19:25:04
【问题描述】:

我向服务器发出请求并获得 JSON 结果:

{"result" => "HTML code"}

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

我尝试将此代码放置在页面上的隐藏块中:

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

接下来呢?如何解析?

【问题讨论】:

标签: angular angular7 angular8


【解决方案1】:

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

app.component.html

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

【讨论】:

  • 我建议谨慎使用innerHTML,因为它会造成内存泄漏
  • @JosephBriggs 你能说什么是替代品,所以它更有用吗?谢谢。
【解决方案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 进行任何恶意活动。因此,我们可以像上面一样创建一个管道并在应用程序的任何地方使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多