Render CSS for innerHtml using angular2

◇◆丶佛笑我妖孽 提交于 2019-12-01 17:43:14
micronyks

Use it with DomSanitizer with bypassSecurityTrustHtml and SafeHtml as shown below,

DEMO : https://plnkr.co/edit/eBlzrIyAl0Il1snu6WJB?p=preview

import { DomSanitizer } from '@angular/platform-browser'

@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
  constructor(private sanitized: DomSanitizer) {}
  transform(value) {
    console.log(this.sanitized.bypassSecurityTrustHtml(value))
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

@Component({
  selector: 'my-app',
  template: `

      <div  [innerHtml]="html | safeHtml"></div>
  `,
})
export class App {
  name:string;
  html: safeHtml;
  constructor() {
    this.name = 'Angular2'
    this.html = `<html xmlns="http://www.w3.org/1999/xhtml"> <head><title>Template Name</title><style type="text/css"> p{ color:red; }</style> </head> <body> <h1>#headding#</h1> <p style="color:red;">#paragraph#</p><a href="#url#">#urltext#</a> </body> </html>`;
  }

}
Günter Zöchbauer

Inject the Sanitizer and apply bypassSecurityTrustHtml(value: string) : SafeHtml to the HTML content as demonstrated in https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html to make Angular2 aware that you trust the content.

See also In RC.1 some styles can't be added using binding syntax

I did it without any pipes and just by injecting DomSanitizer and SafeHtml into my component and running bypassSecurityTrustHtml on my markup string. This allowed me to keep my inline styles from being parsed out.

import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
    selector: "foo",
    templateUrl: "./foo.component.html"
})

export class FooComponent { 
    html: SafeHtml;
    constructor(private sanitizer: DomSanitizer) {
        this.html = this.sanitizer.bypassSecurityTrustHtml('<span style="color:##0077dd">this works</span>');
    }
}

and in foo.component.html template

<div [innerHtml]="html"></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!