如何在Angular2组件中使用JavaScript文件? [英] How to use JavaScript file in Angular2 component?

查看:77
本文介绍了如何在Angular2组件中使用JavaScript文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须嵌入一个小部件,该小部件在加载时执行.在普通的html页面中,我将放置脚本:

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>

然后我将 div 用作占位符:

<div name="rectangle></div>

现在的问题是我不能只将 script 放到模板中,因为它将被删除.同样, rectangleDrawing.js 不会将自身导出为模块.

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.

我该怎么做?

推荐答案

它可能不是最优雅的选择,但它可以工作.只需将其放入您的组件中即可:

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

这篇关于如何在Angular2组件中使用JavaScript文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆