7

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.

0

3 Answers 3

19

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>
Sign up to request clarification or add additional context in comments.

2 Comments

I am also stuck with this issue. I have applied this process but so far no luck.
Inline styles present in string html content is not loading in Inner HTML content.
9

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. :) :) :)

Comments

1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.