0

Can anyone help me how to call a function from external js file inside my angular2 component. Below is my code snippet, when I am trying to load the application it is throwing App is undefined error.

Here is my component code:

import { Component, OnInit, AfterContentInit } from '@angular/core';

@Component({
    selector: 'test',
    templateUrl: './test.html'
})

export class TestComponent implements OnInit {

    constructor() { }

    ngOnInit() {

    }

    ngAfterViewInit() {
        App.handleInit();
    }
}

here is my script inside app.js:

var App = function() {
    var handleInit = function() {
        console.log("Hello world");
    };
}();

When we are calling a function inside ngAfterViewInit it is throwing App is undefined error.

We are importing app.js file inside vendor.ts and we are using webpack. Here app.js is loading fine but function was not working.

Please help us with a solution.

Thanks in advance.

Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
Surya
  • 27
  • 8

2 Answers2

0

You can access like that. does this help

import { Component, OnInit, AfterContentInit } from '@angular/core';
import '../../../../js/app.js'; //just example set this based on your path
declare var App: any;

@Component({
    selector: 'test',
    templateUrl: './test.html'
})
export class TestComponent implements OnInit {

    constructor() { }

    ngOnInit() { }

    ngAfterViewInit() {
        this.handleInit();
    }

    hadeleInit() {
        new app.handleInit();
    }
}
ndsmyter
  • 6,535
  • 3
  • 22
  • 37
Shailesh Ladumor
  • 7,052
  • 5
  • 42
  • 55
0

You have to just simply define App variable in your component as below.

declare var App: any;
@Component({
   .....
})

And now your below call will work.

ngAfterViewInit() {
    App.handleInit();
}