Piyush Jain
Piyush Jain

Reputation: 1881

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

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?

Upvotes: 181

Views: 350148

Answers (10)

Rodrigo Furlaneti
Rodrigo Furlaneti

Reputation: 21

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');  
    }   
   

  }

Upvotes: 0

KavehRSA
KavehRSA

Reputation: 1

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');

Upvotes: 0

Predator13
Predator13

Reputation: 271

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

Upvotes: 3

d1fficult
d1fficult

Reputation: 1073

- 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

Upvotes: 6

tony2tones
tony2tones

Reputation: 1670

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.

Upvotes: 0

Aakash Goplani
Aakash Goplani

Reputation: 1354

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

Upvotes: 8

Aravind
Aravind

Reputation: 41533

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';

Upvotes: 146

Rahul Singh
Rahul Singh

Reputation: 19622

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.

Upvotes: 49

Nagnath Mungade
Nagnath Mungade

Reputation: 1009

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

Upvotes: 54

crash
crash

Reputation: 4512

You can either

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

or

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

Upvotes: 22

Related Questions