Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Under my Anglar 5 app, I have a js script file which I want to load dynamically after the loading of my component view,

this is because my script acts with my component template, and need to have the view loaded to run

I have tried this :

export class MyComponent implements AfterViewInit{
   title = 'app';
   ngAfterViewInit() {
     this.loadScript('http://www.some-library.com/library.js');
     // OR THIS
     this.loadScript('../assets/js/my-library.js');
   }
  }

  public loadScript(url: string) {
    const body = <HTMLDivElement> document.body;
    const script = document.createElement('script');
    script.innerHTML = '';
    script.src = url;
    script.async = false;
    script.defer = true;
    body.appendChild(script);
  }
}

But it still loads my js before the loading of my component HTML file. , and this results on the non-running of my script.

(i see it in the body but in reality, it's not working)

My purpose is to load my js file after my component is loaded.

Suggestions ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
275 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use the AfterContentChecked LifeCycle.

AfterContent hooks AfterContent hooks are similar to the AfterView hooks. The key difference is in the child component.

-The AfterView hooks concern ViewChildren, the child components whose element tags appear within the component's template.

-The AfterContent hooks concern ContentChildren, the child components that Angular projected into the component.

Another approach:

I solved this a long time ago with:

ngAfterViewInit() {
    setTimeout(() => {
        doSomething();
    }, 0);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...