[英]How to Include JS File To Component in Angular
我有很多组件,我想每个都包含 js 文件。 我必须使用第 3 方 js 文件,并且此 js 文件特定于任何组件。 我的意思是这些 js 文件不是全局的,它们是组件特定的。 所以,我想在组件中包含一个 js 文件。
如何将 js 文件包含到组件中?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<base href="/">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body class="fixed-navbar">
<div class="site">
<app-root></app-root>
</div>
<script src="assets/plugins/jquery/jquery.min.js"></script>
<script src="assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script></script>
<!-- Component Specific JS Files Have To Come Here -->
<!-- Component Specific JS Files Have To Come Here -->
<!-- Component Specific JS Files Have To Come Here -->
<!-- Component Specific JS Files Have To Come Here -->
<!-- Component Specific JS Files Have To Come Here -->
</body>
</html>
<p> Post 1</p>
<p> Post 2 </p>
<p> Post Bla bla bla </p>
<!-- This scripts is only for this component -->
<!-- This js section has to go to specific place in index.html where i type -->
<script src="/assets/plugins/parallax/parallax.min.js"></script>
<script src="/assets/plugins/easypiechart/jquery.easypiechart.min.js"></script>
<script>
$(function () {
$('.easypiechart').easyPieChart();
});
</script>
<!-- Angular doesn't include these scripts to page -->
<p> User 1 </p>
<p> User2 </p>
<p> User Bla bla bla </p>
<!-- This scripts is only for this component -->
<!-- This js section has to go to specific place in index.html where i type -->
<script src="/assets/plugins/anotherjs/anotherjs.min.js"></script>
<script src="/assets/plugins/chart2/jquery.chart2.min.js"></script>
<!-- Angular doesn't include these scripts to page -->
我无法在 *.component.html 中使用“ <script>
”标签添加 js 文件
Angular 不同意这种用法。
以防万一,如果有人在 2022 年还在苦苦挣扎,他/她想在任何一个组件中添加 JS 文件。 我就是这样做的:
在 component.ts 文件中:
ngOnInit(): void {
let node = document.createElement('script');
node.src = "https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js";//Change to your js file
node.type = 'text/javascript';
node.async = true;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
}
您不能在模板中添加外部文件。
您可以将它们添加到index.html
或angular-cli.json
scripts
中
理想情况下,如果可能的话,您不应包含整个脚本,而应使用节点模块,并根据需要import
其import
相应的组件ts
在Angular组件中包含jQuery会导致痛苦,但是如果您真的确定要沿着那条路径前进,则可以在组件的TypeScipt文件而不是模板中进行操作。
首先,您需要将jQuery安装到您的应用程序。
npm install jquery --save
在您的angular-cli.json中添加:
],
"scripts": ["../node_modules/jquery/dist/jquery.min.js"],
现在在app.component.ts中,您将需要导入jQuery:
import * as $ from "jquery"
现在您可以在init之后编写jQuery
ngOnInit() {
$...add your code here...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.