How do I include a JavaScript script file in Angular and call a function from that script?

JavascriptAngular

Javascript Problem Overview


I have a JavaScript file called abc.js that has a 'public' function called xyz(). I want to call that function in my Angular project. How do I do that?

Javascript Solutions


Solution 1 - Javascript

Refer the scripts inside the angular-cli.json (angular.json when using angular 6+) file.

"scripts": [
    "../path" 
 ];

then add in typings.d.ts (create this file in src if it does not already exist)

declare var variableName:any;

Import it in your file as

import * as variable from 'variableName';

Solution 2 - Javascript

In order to include a global library, eg jquery.js file in the scripts array from angular-cli.json (angular.json when using angular 6+):

"scripts": [
  "../node_modules/jquery/dist/jquery.js"
]

After this, restart ng serve if it is already started.

Solution 3 - Javascript

Add external js file in index.html.

<script src="./assets/vendors/myjs.js"></script>

Here's myjs.js file :

var myExtObject = (function() {

    return {
      func1: function() {
        alert('function 1 called');
      },
      func2: function() {
        alert('function 2 called');
      }
    }
  
})(myExtObject||{})
  
  
var webGlObject = (function() { 
    return { 
      init: function() { 
        alert('webGlObject initialized');
      } 
    } 
})(webGlObject||{})

 

Then declare it is in component like below

demo.component.ts

declare var myExtObject: any;
declare var webGlObject: any;
    
constructor(){
    webGlObject.init();
}

callFunction1() {
    myExtObject.func1();
}
        
callFunction2() {
    myExtObject.func2();
}

demo.component.html

<div>
    <p>click below buttons for function call</p>
    <button (click)="callFunction1()">Call Function 1</button>
    <button (click)="callFunction2()">Call Function 2</button>
</div>

It's working for me...

Solution 4 - Javascript

You can either

import * as abc from './abc';
abc.xyz();

or

import { xyz } from './abc';
xyz()

Solution 5 - Javascript

I resolved this issue by adding "allowJs": true within "compilerOptions" in tsconfig.json file!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPiyush JainView Question on Stackoverflow
Solution 1 - JavascriptAravindView Answer on Stackoverflow
Solution 2 - JavascriptRahul SinghView Answer on Stackoverflow
Solution 3 - JavascriptNagnath MungadeView Answer on Stackoverflow
Solution 4 - JavascriptcrashView Answer on Stackoverflow
Solution 5 - JavascriptAakash GoplaniView Answer on Stackoverflow