Orlando
Orlando

Reputation: 975

How do you call a function inside an external js file from the index.html in angular2 using angular cli?

I am using angular2 with angular cli. When building my distribution package I am testing the package built for me using http-server. As a reference I am building the package using the following command:

ng build --prod --aot

Once I load the built package I am getting the following error:

ReferenceError: addToHomescreen is not defined

This function is located inside an external js file that I have included inside the angular-cli.json config file:

"scripts": [
    "js/addtohomescreen.js"
],

(The physical js file is located inside the src/js/ directory)

Inside the index.html file i am calling the addtohomescreen() function using the following code:

<script>addToHomescreen();</script>

I don't have any references to the external js file since it gets bundled and cant be found. As far as the function inside the external js file it DOES exist and WORKS FINE because I've used this script previously in a normal html page.

Im fairly new to angular and this is my first package to build any help on what I might be missing would be greatly appreciated. Thanks.

Upvotes: 0

Views: 1058

Answers (2)

Michael Kang
Michael Kang

Reputation: 52847

If you are using modules and module loaders, you can define your function in a module, and import it where you need it. There is no need to include a script tag to load it.

addtohomescreen.ts

export function addToHomeScreen(){
    ...
}

main.ts

import { addToHomeScreen } from './addtohomescreen';

addToHomeScreen();

Upvotes: 0

Vova Bilyachat
Vova Bilyachat

Reputation: 19484

This is wrong approach. You should never include anything to you html files. Right now issue is that script is simply not loaded yet, and it will be loaded a bit later with webpack.

If you want to call this method you need to do it in your angular application.

So to solve this problem you would need to call your function from AppComponent or any other.

But again you cant simply call it since its typescript so you would need to define type inside of typings.d.ts which is in src folder(If not just create it) like this:

declare function addToHomescreen();

Last option if you still want to use it inside of html, then put script to assets folder (And do not include in angular-cli). Include it in html

  <script src="/assets/addtohomescreen.js"></script>

Call it.

Upvotes: 1

Related Questions