script tag in angular2 template / hook when template dom is loaded

Script tags in component templates are removed. A workaround is to create the script tag dynamically in ngAfterViewInit()

See also https://github.com/angular/angular/issues/4903

constructor(private elementRef:ElementRef) {};

ngAfterViewInit() {
  var s = document.createElement("script");
  s.type = "text/javascript";
  s.src = "http://somedomain.com/somescript";
  this.elementRef.nativeElement.appendChild(s);
}

See also https://stackoverflow.com/a/9413803/217408

A better way might be to just use require() to load the script.

See also script tag in angular2 template / hook when template dom is loaded

Leave a Comment