Andrey Mykhaylov Andrey Mykhaylov - 1 year ago 771
HTML Question

Angular2 dynamically insert script tag

I'm getting from server content into json object field, where it is html, and tags, and I want to execute it like this:

[innerHtml]="content | sanitize", but tags do not executes. Is it possible to make it work?

My sanitize pipe looks like this:

import {Pipe} from '@angular/core';
import {DomSanitizationService} from '@angular/platform-browser';

name: 'sanitize',
pure: true
export class Sanitize {
constructor(private sanitizer: DomSanitizationService) {


transform(html: string) {

return this.sanitizer.bypassSecurityTrustHtml(html);

I know, that there is bypassSecurityTrustScript function in DomSanitizationService, but how can I use it in my case?

Answer Source

It's not an angular 2's problem, script tags inserted via innerHTML are not executed.

If you have html string that contains script tags insert it this way:

const fragment = document.createRange().createContextualFragment(yourHtmlString);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download