I have this module which componentize the external library together with additional logic without adding the <script>
tag directly into the index.html:
import 'http://external.com/path/file.js'
//import '../js/file.js'
@Component({
selector: 'my-app',
template: `
<script src="http://iknow.com/this/does/not/work/either/file.js"></script>
<div>Template</div>`
})
export class MyAppComponent {...}
I notice the import
by ES6 spec is static and resolved during TypeScript transpiling rather than at runtime.
Anyway to make it configurable so the file.js will be loading either from CDN or local folder? How to tell Angular 2 to load a script dynamically?
I have done this code snippet with the new renderer api
And then call it like this
StackBlitz
I have modified @rahul kumars answer, so that it uses Observables instead:
@d123546 I faced the same issue and got it working now using ngAfterContentInit (Lifecycle Hook) in the component like this :
In my case, I've loaded both the
js
andcss
visjs
files using the above technique - which works great. I call the new function fromngOnInit()
Note: I could not get it to load by simply adding a
<script>
and<link>
tag to the html template file.@rahul-kumar 's solution works good for me, but i wanted to call my javascript function in my typescript
I fixed it by declaring it in my typescript :
And now, i can call foo anywhere in my typecript file
You can load multiple scripts dynamically like this in your
component.ts
file:and call this method inside the constructor,
Note : For more scripts to be loaded dynamically, add them to
dynamicScripts
array.