I am creating an Angular application using Angular 4 and the CLI. I am trying to add the SkyScanner search widget into one of my components.
Part of the implementation requires the addition of a new external script:
<script src="https://widgets.skyscanner.net/widget-server/js/loader.js" async></script>
I am not sure of the correct way to reference this file. If I add the script into my index.html file, the widget doesn't load unless a full page refresh is performed. I assume the script tries to manipulate the DOM on load and the elements don't exist when the script runs.
What is the correct way to load the script only when the component containing the Skyscanner widget is loaded?
Note: This is specially for external js links! Step 1. Add your angular script into the index.html file at the bottom of your body is recommended! I tried all other ways but failed.
Next there are two ways to do this... In Anguar5 use inside your component folder at the top type in this code
and then inside your class call the method you need. For example
and this should run your code! The other way which might work in older version. I have not checked!
If you are not getting my code then also give try to this link too.
Hope this helps!
add
loader.js
to your assets folder then in yourangular-cli.json
then add this to your
typings.d.ts
and you will be able to use it
Try to load external JavaScript on component load as below :
You can create your own directive to load script as below
And you can use it anywhere in your components template as below
For example, to dynamically load JQuery in your component, insert below code in your component's template
I have done this code snippet
And then call it like this
EDIT: With new renderer Api it can be written like this
StackBlitz
I had the same problem, but in my case, I was importing 10 libraries at the end of the html file, and these libraries have a lot of methods, listeners, events, and more, and in my case I didn't need to call a method specifically.
The example about what I had:
As mentioned, it didn't work. Then, I find somehing that helped me: Milad response
Remove the script calls in the app.component.html. You have to link these scripts in the app.component.ts file.
In ngOnInit(), use a method to append the libraries, for example:
``
It functions for me. I use Angular 6, hope it helps.