1

I angular app I have form component which is dependent on an external script to work properly,

I know that to include the external script in the angular we can do one of the following:-

  1. make an entry in angular.json file
  2. include the script in index.html
  3. include the script file in component.html file
  4. import the script in component.ts file

All the above method include script globally, and it does not work when the component is not loaded.

I want script attached to the component to run every time it is loaded/routed. all CSS is working fine.

Is there any way to make external script local to component and re-run the script every time it is loaded?

Rahul
  • 975
  • 9
  • 25
  • There is this question of how to dinamically load a script in angular https://stackoverflow.com/questions/34489916/how-to-load-external-scripts-dynamically-in-angular – Eduardo Vargas Jan 31 '19 at 17:09

4 Answers4

3

Sound like a case for dynamic import expressions. They look like this (quoting the article):

import("./widget").then(widget => {
    widget.render(container);
});

renderWidget();
Karol Majewski
  • 23,596
  • 8
  • 44
  • 53
0

A sample is created at https://stackblitz.com/edit/angular-hadyfy which outlines how script execution can be included only to a desired component (c1 component in the sample).

Let me know if this solves your question.

Essentially the idea here is to get back the basics of loading a script element child to document ==> head element.

    ngAfterViewInit() {
let url = "assets/c1.js";  //external script url
let head = document.getElementsByTagName("head")[0];
let scrs = head.getElementsByTagName("script");
for(let i=0;i<scrs.length; i++){     
  let scr = scrs[i];

  if(scr.outerHTML.indexOf(url) >0){
    head.removeChild(scr);
  }
}
    let script = document.createElement("script");
    script.src = url;
    script.type ="text/javascript";
    script.async = true;
    script.defer = true;
    head.appendChild(script);

}

-1

You can try ngZone and run your script outside angular

-1

Try to look into that, guy there described how to dynamically download module (js file) and use it, so you can do the same from, for example, ngOnInit or ngAfterViewInit hook in your component.

Amir Arbabian
  • 3,419
  • 1
  • 6
  • 12