1

I'm writing an Angular 2 application, that in some parts needs to render HTML that is loaded from an external API.

This works fine for pure, static HTML by using angulars [innerHTML] directive:

<div [innerHtml]="htmlToBeRendered"> </div>

The HTML that is beeing injected is loaded from an Content Management System. Sometimes this HTML needs to have some Javascript-Code for pure "UI" purposes (some simple DOM-Manipulation within the injected HTML). This will be vanilla JS and won't rely on some other frameworks like JQuery.

Is there a way to keep this JS code while binding it to the dom via angular? Currently all JS code is beeing removed by Angular.

I know that this is a security feature, but the API from where the HTML is loaded can be considered a "safe" source.

Simon
  • 296
  • 4
  • 17

1 Answers1

0

I believe you can use the DomSanitizer for this use-case. This service has a bypassSecurityTrustHtml method which is specifically designed for your problem:

@Component({
    selector: 'test',
    template: `<div [innerHtml]="htmlToBeRendered"> </div>`
})
export class TestComponent {

   public htmlToBeRendered: SafeHtml;

   constructor(public sanitizer: DomSanitizer, public htmlService: SomeApi){}

   public getStaticHtml(): void {
      this.htmlService.getStaticHtml().subscribe((html: string) => {
        this.htmlToBeRendered = this.sanitizer.bypassSecurityTrustHtml(html);
      });
   } 

}

For more info, you can look at this answer of me as well

Community
  • 1
  • 1
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • This is working if I try to invoke a method on the window object like this: --- --- But if I try to invoke my own method that is declared within a script-tag it won't work: --- --- – Simon Jan 31 '17 at 09:24
  • @Simon i'm also having exactly same issue. Since you noticed it few months back, i guess you would have discovered the solution, please share. It will be a help. – user1501382 Apr 15 '17 at 08:52