I am trying to render a HTML template using innerHTML and a html + css string I get from SQL.
Template string example:
<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>
Now it renders the HTML fine but it looks like it drops the style tags and just renders the text inside of it.
Example of render:
HTML render part:
<div [innerHtml]="templateBody">
</div>
Home.component.ts parts:
@Component({
selector: "home",
templateUrl: `client/modules/home/home.component.html`,
encapsulation: ViewEncapsulation.Emulated
})
export class HomeComponent implements OnInit{
templateBody: string;
.....other code
}
I have tried it with encapsulation: ViewEncapsulation.Emulated/None etc, tried inline CSS and I tried appending the :host >>> infront of the p tag. They all render the same.
Any suggestions?
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>`;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With