admin管理员组

文章数量:1134571

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?

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?

Share Improve this question edited Aug 9, 2019 at 17:47 George Stocker 57.9k29 gold badges180 silver badges238 bronze badges asked Jun 29, 2017 at 5:59 Piyush JainPiyush Jain 1,8812 gold badges12 silver badges13 bronze badges 0
Add a comment  | 

10 Answers 10

Reset to default 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';

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

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.

You can either

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

or

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

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

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

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

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

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.

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

Add folder js.

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

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

  }

本文标签: How do I include a JavaScript script file in Angular and call a function from that scriptStack Overflow