1

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

1
  • In your title you're saying angular 6, your code is angularJs/angular1... I would suggest learning the basis of angularJs first... Most often the app module is declared in a file called app.js, but that depends on your project structure and file naming... Commented Aug 7, 2018 at 19:13

1 Answer 1

4

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

1 Comment

Happy to help! :)

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.