javascripthtmlangularjsngsanitize

AngularJs sanitizing and displaying html


I am trying to display dynamically html inside a div. However the div ng-bind-html does not display at all (on firefox, chrome and safari).

Looking at the other posts of this website I saw that I have to include ngSanitize.

I found this snippet here https://www.npmjs.com/package/angular-sanitize :

angular.module('myApp', ['ngSanitize']);

However I do not know where I should write this code ... Do you have any idea how I could do it ?

Thank you very much !

Here is my code :

Code in the component.ts:

import { Component, OnInit, SecurityContext } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'app-player-filter',
  templateUrl: './player-filter.component.html',
  styleUrls: ['./player-filter.component.css']
})
export class PlayerFilterComponent implements OnInit {

  text = '<h1>Test</h1><script></script>';
  text_sanitized: SafeHtml;
  constructor(private _sanitizer: DomSanitizer) { }

  ngOnInit() {
      this.text_sanitized = this.htmlProperty;
  }

  public get htmlProperty(): SafeHtml {
      return this._sanitizer.sanitize(SecurityContext.HTML, this.text);
  }

}

Code in the component.html:

<div ng-bind-html="text_sanitized"></div>
Normal: {{text}} Sanitized: {{text_sanitized}}

Output on firefox:

Normal: <h1>Test</h1><script></script> Sanitized: <h1>Test</h1>

Output console:

WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).

The console output shows that the sanitizing operation happenned (confirmed by the output sanitized that got rid of the script). Wierd thing, there is no error shown in the console from having unsafe html displayed...


Solution

  • The 'ng-bind-html' belongs to angularJS(older version before angular 2+) so its not suppose to work or display anything with Angular 6.

    Use [innerHTML] instead as mentioned in Agular Documentation:

    <div [innerHTML]="text_sanitized"></div>