在Angular 2中使用外部JavaScript文件

时间:2018-05-18 12:44:37

标签: javascript angular typescript angular2-template

外部JavaScript文件在angular 2组件内部无效。它显示错误myEObject is not defined

external.component.html

<p id="demo">A Paragraph.</p>
<button type="button" (click)="callFun()">Try it</button>

external.component.ts

import { Component } from '@angular/core';
import '../myExternal.js';

declare var myEObject: any;

@Component({
    selector: 'external-file',
    templateUrl: './external.component.htmll'
})
export class ExternalComponent {

    callFun(){
        myEObject.myFunction();
    }
}

myExternal.js

var myEObject = (function() {

    return {
        func1: function() {
            document.getElementById("demo").innerHTML = "Paragraph changed.";
        }
    } 

})(myEObject||{})

1 个答案:

答案 0 :(得分:0)

  1. 通过终端---

    执行此命令
    npm install jquery --save,
    
    npm install --save-dev @types/jquery
    
  2. 将myExternal.js文件移至资源文件夹