Angular 4中的HTML编码

7
我希望在Angular 4中获取HTML编码方面能得到您的帮助。我在数据库中有一些产品记录,其中fullDescription字段格式如下:
<div align="justify"><span>

使用 <div *ngIf="product" [innerHTML]="product.fullDescription"></div> 我得到了以下输出:

<div align="justify"><span>

作为文本,能否将其呈现为innerHtml而不是文本?

提前致谢。

3个回答

19

在组件的类中,您可以像这样使用HTML实体解码器功能:

toHTML(input) : any {
    return new DOMParser().parseFromString(input, "text/html").documentElement.textContent;
}

并在模板中使用:

<div *ngIf="product" [innerHTML]="toHTML(product.fullDescription)"></div>

1
我也遇到了这个问题。我已经尝试了这个方法,但是目前还没有成功。 - Nadim Hossain Sonet
字符串 HTML 内容中的内联样式在 Inner HTML 内容中无法加载。 - Rajeev Kumar

9

我通过实现管道来完成了它。

创建一个 component.ts 文件,然后在该文件中:

import { Pipe, PipeTransform, SecurityContext } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({ name: 'sanitizeHtml', pure: false })
export class SanitizeHtmlPipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) { }

  transform(data): SafeHtml {
    return this.sanitizer.sanitize(SecurityContext.HTML, data);
  }
}

接下来在app.module.ts中:

  • 导入{ SanitizeHtmlPipe } from './pagecontent/pagecontent.component';

  • 将SanitizeHtmlPipe添加到declarations[]中

最后,在component.html文件中:

<span [innerHTML]="data | sanitizeHtml"></span>

那就交给我吧。:) :) :)

1
上面的解决方案部分解决了我的问题。除了上面的更改,下面的代码更改帮助我正确地将带有内联样式的编码字符串html加载到div中。
HTML代码更改:
<div *ngIf="product" id="divFullDescription" #divFullDescription></div>

Angular组件.ts侧面代码更改:

@ViewChild('divFullDescription', { static: true }) divFullDescription: ElementRef;

loadHtml() {
    this.divFullDescription.nativeElement.innerHTML = 
        this.toHTML('&lt;div align="justify" style="color:red;"&gt;&lt;span&gt;');
}

toHTML(input) : any {
    return new DOMParser().parseFromString(input, "text/html").documentElement.textContent;
}

我希望这可以帮助到某个人。谢谢!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接