Skip to content Skip to sidebar Skip to footer

How To Use JavaScript File In Angular2 Component?

I've to embed a widget, which a executing on load. In a normal html page, I would put the script: And then I would put a di

Solution 1:

  • Put the <script> inside index.html page
  • Put the <div.. markup inside a component template

Probably that script will expose some global variables that you can use inside your component, it depends what's inside and how it works...


Solution 2:

It is probably not the most elegant option, but it works. Just put this into you Component:

ngOnInit() {
    this.loadScript();
}

private loadScript(): void {
    const node = document.createElement('script');
    node.src = 'yourScript.js';
    node.type = 'text/javascript';
    node.async = true;
    node.charset = 'utf-8';
    document.getElementsByTagName('head')[0].appendChild(node);
}

Post a Comment for "How To Use JavaScript File In Angular2 Component?"