Angular 4 script not working after changing route

后端 未结 6 1037
萌比男神i
萌比男神i 2020-12-11 09:59

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

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 10:30

    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

提交回复
热议问题