Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2: including thirdparty js scripts in component [duplicate]

Is there a way to include third party JS scripts inside an Angular2 component instead of including it in index.html?

I have a table component that wraps dataTables. It's the only component that needs the dataTables js/css includes. It would be nice if I could keep my index.html cleaner. The component decorator does let you specify css files.

I tried moving my script tags inside my component html, but that doesn't seem to work.

like image 713
dvulanov Avatar asked Feb 23 '16 06:02

dvulanov


1 Answers

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

import { DOCUMENT } from '@angular/common';
...

constructor(private @Inject(DOCUMENT) document, 
            private elementRef:ElementRef) {};

ngAfterViewInit() {
  var s = this.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

like image 141
Günter Zöchbauer Avatar answered Oct 08 '22 04:10

Günter Zöchbauer