简体   繁体   中英

Use Of External JavaScript file in Angular 2

External JavaScript file is not working inside angular 2 component. It's showing error 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. Execute this command through terminal ---

     npm install jquery --save, npm install --save-dev @types/jquery 
  2. move myExternal.js file to assets folder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM