11

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.

4
  • yes you can load third party css in your required component only in styleUrls. i dont know about .js files Commented Feb 23, 2016 at 6:56
  • dup of stackoverflow.com/questions/34140065/… Commented Feb 23, 2016 at 7:01
  • Have you considered PrimeNG DataTable, it is a native component. primefaces.org/primeng/#/datatable Commented Feb 23, 2016 at 18:06
  • I did look at PrimeNG, I need the print/pdf feature though. Commented Feb 24, 2016 at 13:24

1 Answer 1

13

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

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

12 Comments

this does't seems to work properly angular throws error this.elementRef.nativeElement.append is not a function ? why ?
@PardeepJain I guess the correct function name is appendChild(s) in JS/TS. In Dart it's append(s) and I mixed it up.
I got a ref via: document.getElementById instead. The scripts load, but the js code that needs these scripts doesn't execute properly on initial load (after refresh it works). Really, I don't think this would be a solution even if it worked. My questions was to see if there is a clean/standard "angular way" to include js dependencies only in the components that need them.
No, currently there are only workarounds.
If you make the script source dependent on user input, then you of course open a barn door for XSS attacks. If the string is hardcoded in the applications source code, I don't see a problem.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.