181

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?

0

10 Answers 10

146

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';
Sign up to request clarification or add additional context in comments.

21 Comments

i added path in scripts as "scripts": [ "./assets/common_header_sidebar.js" ]; then in typing.d.ts i wrote declare var commonHeader:any; and then in my ts file i wrote import * as commonHeaderModule from 'commonHeader'; but getting "Cannot find module 'commonHeader'." error
i might sound silly for asking this. but how the file name in the path(declared in angular-cli.json) and declaring name of the object in typing.d.ts file is related. since i am importing from the name of the declared object not the file
can you create a plunker to reproduce
done with the integration it is just that i had to declare the function in my ts file where i was using it and import was not required. Thanks a ton .
@Aravind what if I don't have typing.d.ts file in my Angular 4 project?
|
54

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...

3 Comments

Very thorough example thanks, it worked for me on angular 6. None of the other answers worked.
Fwiw, here are some explanations of what declare does -- essentially "declare is used to tell TypeScript that the variable has been created elsewhere" (from this answer).
I think the index.html file is empty by design and I think you should keep it that way. The ng serve should take care of all javascript files.
50

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.

5 Comments

how do you import on the typescript file?
to import in ts file use - declare var $: any;
angular-cli.json file has been renamed/replaced with angular.json in version 6+ of Angular.
Either this isn't working in 2021 or there is a step missing
What else after adding the file to array? @alansiqueira27 good point
22

You can either

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

or

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

3 Comments

what am i supposed to do when the file is hosted somewhere but not in the local repo?
did you figure this out?
Getting errors in both methods. Well I have a .js file in my project but when I import by first method its give me error in compiling and can't find any module when I use the second method. And I am just using slick slider.
8

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

Comments

6

- Let us assume our script file custom.js looks like this: -

var utilObj = {
    dummyFunc: () => {
        console.log('Calling dummy function!');
    }
}

- Add your javascript/script file in scripts array in angular.json file.

"scripts": [
    "src/custom.js" 
 ],

Should look like this: -

enter image description here

- Add below code snippet in typings.d.ts. If this file doesn't exist, create one in src folder.

declare var utilObj:any;

Keep your variable name similar to property of script file. Here utilObj is the property name.

- Now, You can consume this script/js file directly in your component or .ts file.

You need not import the file in component file or .ts file now as we have given the typing defination for the script file already in typings.d.ts file.

Example: -

ngOnInit() {
  console.log('Starting Application!');
  utilObj.dummyFunc();
}

- Output: -

enter image description here

Comments

3

I was facing similar issue and resolved it by adding my js file to scripts inside options in angular.json file.

And declaring the object I created in JavaScript file in typings.d.ts file.

Here's link that might help you a bit more on this:- https://medium.com/@darediP/communication-between-js-and-ts-files-with-angular-and-electron-6f93cecd179e

Comments

0

This might sound silly, but if you feel that you are properly exporting your JavaScript helper function utils/javaScriptHelperFunction.js

export function javaScriptFunction() {
   // DO HELPER FUNCTION STUFF
}

If you have done your checks as mentioned in the above answers, just close and open your code editor...start with the quick basic troubleshooting before going down the rabbit hole.

Comments

0

I had this problem with including Muuri in my Angular project. I solved it like below: Solution 1: Use the cdn of that script in index.html place those cdns in the head of index.html not at the end of body tag

Solution 2: download those script files and place them in assets folder inside app folder and add script tags in the head of index.html not at the end of body tag.

Solution 3:(Muuri Case Study) first of all install murri(or your intended library) using > npm i muuri then import typings file from murri package in the component import Muuri from '.../node_modules/muuri/src/index'; then use it in ngOnInit method like this: const muuri_grid01 = new Muuri('.muuri-grid-01');

Comments

0

Add folder js. enter image description here

 **JS**

function changeLoading() 
{
    $('body').append(
      '<div id="overlay">' +
      '<img id="loading" src="assets/loading.png">'+
      '</div>'
  );
  setTimeout(function(){
    $('#overlay').remove();
    window.open( link );
  }, 1000); //2 seconds

}
 **CSS**

  #overlay {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    background: #000;
    opacity: 0.8;
    filter: alpha(opacity=80);
}
#loading {
    width: 50px;
    height: 57px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -28px 0 0 -25px;
}
 **HTML**

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<button onclick="changeLoading();" type="button"></button>

}

angular.json enter image description here

Component

import { Component, Inject, OnInit } from '@angular/core';  
import { AppService } from './app.service';
import { Router } from '@angular/router'; 
import { DOCUMENT } from '@angular/common';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  })
  export class AppComponent implements OnInit{

    constructor(private appService: AppService,
                private _snackBar: MatSnackBar,
                private router: Router,
                @Inject(DOCUMENT) private readonly document: Document) {           };
    
     private addScript(scriptSrc: string) {
                  const script = this.document.createElement('script');
                  script.type = 'text/javascript';
                  script.src = scriptSrc;
                  script.async = true;
                  this.document.head.appendChild(script);
              }
    
    ipAddress:string = '';

    ngOnInit()  
    {  
      this.addScript('js/javascript.js');  
    }   
   

  }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.