Angular 4 script not working after changing route

后端 未结 6 1017
萌比男神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:12

    you need to load your script in ngOnInit(). This is because when angular changes its route then it does not fire document.ready. That's why JS does not called. Adding in ngOnInitwill solve the problem. It loads JS when ever your ngOnInit is being called.

    ngOnInit(){
        $.getScript('src/assets_v2/js/main.js');
        // do rest of your stuff here.
    }
    
    0 讨论(0)
  • 2020-12-11 10:19

    here is an angular way

    export class PagesComponent implements OnInit, OnDestroy {
      routerSubscription: any;
      constructor(private router: Router) {}
    
      ngOnInit() {
        this.recallJsFuntions();
      }
    
      /**
       * @description when we navigate from one page to another `scope of js funtions`
       * finished so we have to call it again.
       */
      recallJsFuntions() {
        this.routerSubscription = this.router.events
          .pipe(filter(event => event instanceof NavigationEnd))
          .subscribe(event => {
            $.getScript('/assets/js/common.js');
          });
      }
    
      ngOnDestroy() {
        this.routerSubscription.unsubscribe();
      }
    }
    
    0 讨论(0)
  • 2020-12-11 10:25

    According to your question I think the problem is with the scripts initialization. Try using:

    $(document).ready(function() {
    
    });
    

    to initialize scripts.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-11 10:30

    This worked for me,

    Add this code in your app.component.ts file

      constructor(private elRef: ElementRef){ 
      
      }
    
      ngOnInit(){
          $.getScript('/assets/js/custom-script.js'); //Add path to your custom js file
      }
    
      observer;
    
      ngAfterViewInit(){
        this.observer = new MutationObserver(mutations => {
          
          console.log('Dom change detected...');
          $.getScript('/assets/js/custom-script.js'); //Add path to your custom js file
    
        });
        var config = { attributes: true, childList: true, characterData: true };
    
        this.observer.observe(this.elRef.nativeElement, config);
      }
    

    If jQuery code giving error, then

    1. Install @types/jquery
    2. Add 'jquery' in types:[ ] list of tsconfig file.

    In angular page doesn't reload every time, but DOM elements can be loaded or removed. In angular routing; components and DOM elements are dynamically loaded but custom script can only loaded once when page refresh, after loading script, any changes in DOM will not affect script.

    For that we have to watch changes in DOM, if there are changes then we load custom script everytime. Mutation Observer detects changes in DOM.

    This solution also work with *ngIf problem, where components loaded on condition.

    0 讨论(0)
  • 2020-12-11 10:38

    try after clear browser history or try it with private browsing

    0 讨论(0)
提交回复
热议问题