2

I am using VS 2015 as my IDE. I have read the following: Angular 2 typescript invoke javascript function

and

Using a Javascript Function from Typescript

and

Using a Javascript Function from Typescript

however, i still don't get the basic.

assuming that i have testing.js and app.component.ts

    var testJs = function () {
    this.asd = 123;

}

testJs.prototype.testing = function (param) {
    console.log(param);
}

How do I use testJs in my app.component.ts? at the moment i try this but failed:

import { Component } from '@angular/core';
interface testJs {
    testing: Function;
}
declare var testJs: testJs;
@Component({
    selector: 'my-app',
    templateUrl: '/mainTemplate.html'
})
export class AppComponent {
    testJs.testing("adsf");
}

I have tried the following and it still does not work as well. enter image description here

and I don't have angular.cli. is it possible to do it without angular.cli?

Community
  • 1
  • 1
jay
  • 1,055
  • 3
  • 15
  • 35

3 Answers3

4

Finally found a way to do it.

  1. in your html file that download the main.js file, put reference to the javascript file in the head tag enter image description here

  2. in your typescript file (in this case i am using angular) do the following:

a. declare the variable :

b. use the funciton in the constructor of the exported class

import { Component } from '@angular/core';
declare function testJs(): any;
@Component({
    selector: 'my-app',
    templateUrl: '/mainTemplate.html'
})

export class AppComponent {
    user: string;
    constructor() {
        testJs.prototype.testFunction();
        this.user = "asdf";
        var x = 90;
    }
}
jay
  • 1,055
  • 3
  • 15
  • 35
3
  1. where is get this testJS.js. Is this external lib? if yes, you need to include it in angular-cli like that:

    "scripts": [ "../node_modules/.../testJS.js" ],

  2. You need to either create typings or at least make dummy type:

    declare var testJS: any;

  3. You can use it afer

eko
  • 39,722
  • 10
  • 72
  • 98
Julia Passynkova
  • 17,256
  • 6
  • 33
  • 32
1

i'm use from eval()
1) before main.js file, put javascript file.
2) use from eval("testFunction()") in your typescript file in angular.

Mehran Kh
  • 11
  • 4