【问题标题】:Html encoding in angular 4角度为 4 的 Html 编码
【发布时间】:2017-09-23 19:21:05
【问题描述】:

在 Angular 4 中的 html 编码方面需要您的帮助。 我在数据库中有一些产品记录,fullDescription 字段采用这种格式:

<div align="justify"><span>

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

<div align="justify"><span>

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

提前致谢。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    在你的组件类中,你可以像这样使用 HTML 实体解码器函数:

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

    并在模板中使用:

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

    【讨论】:

    • 我也被这个问题困住了。我已经应用了这个过程,但到目前为止还没有运气。
    • 字符串 html 内容中存在的内联样式未加载到内部 HTML 内容中。
    【解决方案2】:

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

    创建一个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 中:

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

    • 在声明中添加 SanitizeHtmlPipe[]

    终于在component.html中:

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

    就是这样。 :) :) :)

    【讨论】:

      【解决方案3】:

      上述解决方案部分解决了我的问题。除了上述更改之外,以下代码更改帮助我正确加载具有内联样式的编码字符串 html 到 div。

      HTML 代码更改:

      <div *ngIf="product" id="divFullDescription" #divFullDescription></div>
      

      Angular component.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;
      }
      

      我希望,这可能对某人有所帮助。谢谢!

      【讨论】:

        猜你喜欢
        • 2018-07-20
        • 2018-08-03
        • 2018-02-08
        • 2017-10-20
        • 1970-01-01
        • 2018-06-12
        • 1970-01-01
        • 2018-04-18
        • 2016-04-25
        相关资源
        最近更新 更多