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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

This is working if I try to invoke a method on the window object like this: --- <button onclick="alert('hello')">Click me!</button> --- But if I try to invoke my own method that is declared within a script-tag it won't work: --- <button onclick="doSomething()">Clicke me!</button> <script> function doSomething(){ alert("Hello!"); } </script> ---
@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.

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.