[英]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.