Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html encoding in angular 4

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.

like image 567
dseferlis Avatar asked Sep 23 '17 19:09

dseferlis


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>
like image 85
Saif Avatar answered Oct 06 '22 23:10

Saif


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

like image 28
Nadim Hossain Sonet Avatar answered Oct 07 '22 00:10

Nadim Hossain Sonet


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!

like image 23
Rajeev Kumar Avatar answered Oct 07 '22 00:10

Rajeev Kumar