将JavaScript文件添加到Angular 4组件 [英] Adding JavaScript File to Angular 4 Component
问题描述
我们只是说我制作了一个自定义JavaScript文件,即'custom.js'
Let's just say I make a custom JavaScript file ie 'custom.js'
我如何将其实现为一个组件?
How would I implement this into a Component?
如果我将'custom.js'添加到index.html,那很好但是有什么方法可以将它专门添加到组件中吗?
If I add 'custom.js' to index.html, that's fine but is there any way I can add it specifically to the component?
推荐答案
步骤:1 =>创建并编写你的js代码说 synapse.js 在 / app 文件夹中。应使用 export
关键字导出要在组件中使用的函数或常量。 for ex :
Step: 1=> Create and write your js code say "synapse.js" in /app folder. The function or constant which you to use in a component should be exported using export
keyword. for ex:
synapse.js
export function synapseThrow() {
return 'hello'
}
export const MY_VAR = 'world!';
步骤:2 =>在 angular-cli.json中,在 apps
对象中添加以下部分。
Step: 2=> in angular-cli.json, add the below part in apps
object.
"scripts": ["app/synapse.js"]
步骤:3 =>在 tsconfig.json 中,在 compilerOptions
中添加以下属性。
Step: 3=> in tsconfig.json, add the below property in compilerOptions
.
"allowJs": true
步骤:4 =>在 app.component.ts 中的任何组件中,使用 import >导入 synapse.js 文件code> keyword。
Step: 4=> in any component say in "app.component.ts" import the "synapse.js" file using import
keyword.
app.component.ts
// other imports
import { MY_VAR, synapseThrow } from './synapse';
// other app code here
ngOnInit(){
const returned = MY_VAR;
const returnFunc = synapseThrow();
}
这篇关于将JavaScript文件添加到Angular 4组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!