typescript 角度 4 中的 Html 编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46383424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:55:00  来源:igfitidea点击:

Html encoding in angular 4

angulartypescript

提问by dseferlis

I need your help with html encoding in angular 4. I have some product records in database, with fullDescription field in this format:

我需要你在 angular 4 中进行 html 编码方面的帮助。 我在数据库中有一些产品记录,fullDescription 字段采用以下格式:

<div align="justify"><span>

Using <div *ngIf="product" [innerHTML]="product.fullDescription"></div>I'm getting the following output:

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

<div align="justify"><span>

as text. Is this possible to render this as the innerHtml and not as text?

作为文本。这是否可以将其呈现为 innerHtml 而不是文本?

Thanks in advance.

提前致谢。

回答by Saif

In your component's class, you can use HTML entity decoder function like this:

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

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

and in the template use:

并在模板中使用:

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

回答by Nadim Hossain Sonet

I have done it by implementing pipe.

我已经通过实施管道做到了。

Create a component.ts file and in that file:

创建一个 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);
  }
}

Then in app.module.ts:

然后在 app.module.ts 中:

  • import { SanitizeHtmlPipe } from './pagecontent/pagecontent.component';

  • add SanitizeHtmlPipe inside declarations[]

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

  • 在声明中添加 SanitizeHtmlPipe[]

Finally in component.html:

最后在 component.html 中:

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

Thats it. :) :) :)

而已。:) :) :)