0

I have JSAngular2Demo.js in apps folder which contains a simple function :-

function sample()
{
    alert("sample");

}

I want to call this function from apps.component.ts

For this:-

import {Component} from "@angular/core";
import "app/JSAngular2Demo.js";

declare function sample(): any;
@Component({ selector: "my-app", templateUrl:"app/UIAngular.html" })
export class AppComponent {
    strWelcomeMessage: string = "Welcome Sagar";
    constructor() {
        sample.prototype.sample();
    }
}

But this function is not getting called.

What can be the possible reason?

1
  • Why aren't you using Typescript? Commented Jun 21, 2017 at 6:27

1 Answer 1

1

Export Your function in JSAngular2Demo.js like:-

   module.exports = {
        sample: function() {

           alert("sample");
        }

    }

apps.component.ts

import {sample} from './JSAngular2Demo';


    @Component({ selector: "my-app", templateUrl:"app/UIAngular.html" })
    export class AppComponent {
        strWelcomeMessage: string = "Welcome Sagar";
        constructor() {
          sample();
        }
    }

And Add "allowJs": true, to tsconfig.json file to allow js files under compilerOptions

Sign up to request clarification or add additional context in comments.

3 Comments

import {sample} from './JSAngular2Demo'; is not working
Have you tried adding a reference of JsAngularDemo.js in Index.html ?
import statement will work if you add allowJs:true in tsconfig file under compilerOptions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.