Html encoding in angular 4

Viewed 20770

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.

3 Answers

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>

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('&lt;div align="justify" style="color:red;"&gt;&lt;span&gt;');
}

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

I hope, this may help someone. Thanks!

Related