Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call pure javascript function from Angular 2 component

I have one file that have dozens javascript functions. What I want to do is to import that file into Angular 2 component and run init() function that is defined in "external.js" file.

import { Component, AfterViewInit } from '@angular/core';

import "../../../../assets/external.js";

@Component({
    selector: 'app-component',
    templateUrl: 'app.component.html'
})
export class ComponentNameComponent implements AfterViewInit {
    constructor() { }

    ngAfterViewInit(): void {
      // invoke init() function from external.js file
    }
}

external.js is loaded using import and in ngAfterViewInit() I want to invoke init() function that is in external.js that calls all other methods in that external file.

Here is part of external.js:

function init() {
  callFunction1();
  callFunction2();
}
like image 912
Haris Hajdarevic Avatar asked Nov 16 '16 14:11

Haris Hajdarevic


People also ask

Does angular 2 use JavaScript?

Angular 2 is an open source JavaScript framework to build web applications in HTML and JavaScript. This tutorial looks at the various aspects of Angular 2 framework which includes the basics of the framework, the setup of Angular and how to work with the various aspects of the framework.

How do you call a component function from outside the app?

To call component function from outside the app with Angular, we need to use NgZone . import { Component, NgZone, OnInit, OnDestroy } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "app.

Can JavaScript call TypeScript function?

TypeScript supports the existing JavaScript function syntax for declaring and calling it within the program or the code snippet.


2 Answers

You can import and declare your external object. after then you can use it in your component.

import 'external.js'
declare var myExtObject: any;

I made an example in plunker: https://plnkr.co/edit/4CrShwpZrDxt1f1M1Bv8?p=preview

Hope this helps.

like image 172
hakany Avatar answered Oct 04 '22 17:10

hakany


Checkout my git project of angular 6 - I used this in login component -

https://github.com/gajender1995/Angular-HighChart-Auth

exter.js

define(["require", "exports"], function(require, exports){
   exports.value = "aaa";
   exports.gajender = function(){console.log(2)}; 
});

login.component.ts

 import * as MyModule from './exter.js';

 console.log('my value is', MyModule.gajender());

In tsconfig Add

"allowJs": true
like image 36
Gajender Singh Avatar answered Oct 04 '22 16:10

Gajender Singh