How to use JavaScript file in Angular2 component?

2019-09-11 10:27发布

问题:

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

<script src="rectangleDrawing.js"></script>

And then I would put a div as a placeholder:

<div name="rectangle></div>

The problem is now that I can't just put the script into the template, because it will be removed. Also the rectangleDrawing.js, is not exporting itself as a module.

How can I do this?

回答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...



回答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);
}