从Angular 2组件中调用纯javascript函数
Call pure javascript function from Angular 2 component
我有一个文件,有几十个javascript函数。我要做的是将该文件导入Angular 2的组件,并运行在"external.js"文件中定义的init()函数。
import { Component, AfterViewInit } from '@angular/core';
import "../../../../assets/external.js";
@Component({
selector: 'app-component',
templateUrl: 'app.component.html'
})
export class ComponentNameComponent implements AfterViewInit {
constructor() { }
ngAfterViewInit(): void {
// invoke init() function from external.js file
}
}
external.js是使用import加载的,在ngAfterViewInit()中我想调用init()函数,它在external.js中调用该外部文件中的所有其他方法。
这是external.js的一部分:
function init() {
callFunction1();
callFunction2();
}
可以导入和声明外部对象。然后你就可以在你的组件中使用它了。
import 'external.js'
declare var myExtObject: any;
我在plunker中做了一个例子:https://plnkr.co/edit/4CrShwpZrDxt1f1M1Bv8?p=preview
Checkout我的angular 6 git项目-我在login组件中使用了这个-
https://github.com/gajender1995/Angular-HighChart-Authexter.js
define(["require", "exports"], function(require, exports){
exports.value = "aaa";
exports.gajender = function(){console.log(2)};
});
login.component.ts
import * as MyModule from './exter.js';
console.log('my value is', MyModule.gajender());
tsconfig Add
"allowJs": true
需要像这样导入javascript文件:
import * as myjsname from '../../mypathto/myjavascriptfile.js';
从javascript文件中调用一个例程,如下所示:
myjsname.myjsroutine();
重要的是,你需要在javascript文件中使用export关键字,像这样:
export function myjsroutine() {
//my js code
}
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 正在全局范围中查找JavaScript函数
- 如何将输入(type=text)从html表单传递到javascript函数
- 如何调用这个匿名 JavaScript 函数
- 通过Ajax将JavaScript函数传递给PHP文件
- 在javascript函数中设置全局变量
- 如何在执行此特定onclick事件时执行JavaScript函数
- 使用javascript函数在页面初始化后加载jquery
- javascript函数同步
- 如何将一个JavaScript函数回调为多个函数
- 在javascript函数中使用php变量
- 代码背后调用一个JavaScript函数的按钮点击-C#
- 将JavaScript函数与HTML分离
- 组合两个javascript函数
- 在 Java 中的 JavaScript 函数中插入 Wicket 值
- javascript函数内部的代码用逗号而不是分号分隔
- href属性内的javascript函数
- 使用html表单中的参数调用JavaScript函数
- 分析Javascript函数中的多个对象
- javascript函数的:和=之间的区别