I need your help with html encoding in angular 4. I have some product records in database, with fullDescription field in this format:
<div align="justify"><span>
Using <div *ngIf="product" [innerHTML]="product.fullDescription"></div>
I'm getting the following output:
<div align="justify"><span>
as text. Is this possible to render this as the innerHtml and not as text?
Thanks in advance.
In your component's class, you can use HTML entity decoder function like this:
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>
I have done it by implementing pipe.
Create a component.ts file and in that file:
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:
import { SanitizeHtmlPipe } from './pagecontent/pagecontent.component';
add SanitizeHtmlPipe inside declarations[]
Finally in component.html:
<span [innerHTML]="data | sanitizeHtml"></span>
Thats it. :) :) :)
Above solution partially solved my issue. Along with above changes, below code changes helped me to load encoded string html with inline styles to div correctly.
Html code changes:
<div *ngIf="product" id="divFullDescription" #divFullDescription></div>
Angular component.ts side code changes:
@ViewChild('divFullDescription', { static: true }) divFullDescription: ElementRef;
loadHtml() {
this.divFullDescription.nativeElement.innerHTML =
this.toHTML('<div align="justify" style="color:red;"><span>');
}
toHTML(input) : any {
return new DOMParser().parseFromString(input, "text/html").documentElement.textContent;
}
I hope, this may help someone. Thanks!
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