向Angular 4组件添加JavaScript文件
假设我制作了一个自定义JavaScript文件,即“custom.js” 如何将其实现到组件中向Angular 4组件添加JavaScript文件,javascript,angular,typescript,Javascript,Angular,Typescript,假设我制作了一个自定义JavaScript文件,即“custom.js” 如何将其实现到组件中 如果我将“custom.js”添加到index.html中,这很好,但是有没有办法专门将其添加到组件中?尝试声明custom.js文件中的变量 尝试声明custom.js文件中的变量 步骤:1=>在/app文件夹中创建并编写js代码,比如synapse.js。要在组件中使用的函数或常量应使用export关键字导出。例如: synapse.js 步骤:2=>在angular-cli.json中,在app
如果我将“custom.js”添加到index.html中,这很好,但是有没有办法专门将其添加到组件中?尝试声明custom.js文件中的变量
尝试声明custom.js文件中的变量 步骤:1=>在/app文件夹中创建并编写js代码,比如synapse.js。要在组件中使用的函数或常量应使用export关键字导出。例如: synapse.js 步骤:2=>在angular-cli.json中,在apps对象中添加以下部分 步骤:3=>在tsconfig.json中,在compilerOptions中添加以下属性 步骤:4=>在任何组件中,比如在app.component.ts中,使用import关键字导入synapse.js文件 app.component.ts 步骤:1=>在/app文件夹中创建并编写js代码,比如synapse.js。要在组件中使用的函数或常量应使用export关键字导出。例如: synapse.js 步骤:2=>在angular-cli.json中,在apps对象中添加以下部分 步骤:3=>在tsconfig.json中,在compilerOptions中添加以下属性 步骤:4=>在任何组件中,比如在app.component.ts中,使用import关键字导入synapse.js文件 app.component.ts 试着这样做: 将js文件放入路径:assets/js/custom.js 为组件编写代码 ts文件
export class MyComponent implements AfterViewChecked {
constructor(private elementRef: ElementRef) {
}
ngAfterViewChecked() {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "../assets/js/custom.js";
this.elementRef.nativeElement.appendChild(s);
}
}
试着这样做:
将js文件放入路径:assets/js/custom.js
为组件编写代码
ts文件
export class MyComponent implements AfterViewChecked {
constructor(private elementRef: ElementRef) {
}
ngAfterViewChecked() {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "../assets/js/custom.js";
this.elementRef.nativeElement.appendChild(s);
}
}
这个文件会有什么?动画,等等。例如,在导航栏中移动时,您不能仅从组件定义内部导入吗?不过,我想这需要它是一个模块。是否可以将您的custom.js更改为一个模块?能否显示您的.js的外观以及您在项目中保存它的位置?此文件有哪些内容?动画等。例如,在导航栏中移动时,您不能仅从组件定义内部导入吗?不过,我想这需要它是一个模块。是否可以将custom.js更改为一个模块?能否展示一下.js的外观以及在项目中的存放位置?
"scripts": ["app/synapse.js"]
"allowJs": true
// other imports
import { MY_VAR, synapseThrow } from './synapse';
// other app code here
ngOnInit(){
const returned = MY_VAR;
const returnFunc = synapseThrow();
}
export class MyComponent implements AfterViewChecked {
constructor(private elementRef: ElementRef) {
}
ngAfterViewChecked() {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "../assets/js/custom.js";
this.elementRef.nativeElement.appendChild(s);
}
}