Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 script not working after changing route

Tags:

angular

while changing the routes to homepage, javascript and jquery code is not loading in Angular 5

like image 435
Sr.Nitish Avatar asked Dec 02 '22 10:12

Sr.Nitish


1 Answers

first, add your script to a .js file and save it under angular.json like below

"scripts": ["src/assets/js/modelsupport.js"],

add below code in you component.ts that you want it to work

url could start with src/assets or assets according to your angular version

url = "assets/js/modelsupport.js";

after that include below code in ngOnInit() or where ever you want to call

this.loadAPI = new Promise(resolve => {
  console.log("resolving promise...");
  this.loadScript();
});

after that add loadScript() function in you class

public loadScript() {
    console.log("preparing to load...");
    let node = document.createElement("script");
    node.src = this.url;
    node.type = "text/javascript";
    node.async = true;
    node.charset = "utf-8";
    document.getElementsByTagName("head")[0].appendChild(node);
}

Hope you could solve your problem

like image 64
Malith Kuruwita Avatar answered Dec 04 '22 00:12

Malith Kuruwita