Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular4 how to call a function in a external js

I have a jscript which displays a log to the console:

x.js contains

function open() {
    console.log('this a function');
}

in index.html of my app

<script src="x.js"></script>

in my component

declare var xJS : any;;

@Component({
   selector: 'employerfile',
   templateUrl: './employerfile.component.html'
})

export class EmployerFileComponent
    .....
    openURL() {
       xJS.open();  
    }
}

in html

<a (click)="openURL()"> click </a>

When I execute this code, I get an exception@

Original exception: xJS is not defined

How can I call this external function?

like image 844
Florence Avatar asked Jun 19 '17 06:06

Florence


2 Answers

Importing your file like this <script src="x.js"></script> will not work.

You have to import it in the following way:

import * as xJS from './x.js';

If it will not work, the alternative way is to use System.import:

declare var System: any; 

System.import('./x.js')
    .then(xJS => {
        xJS.open();
    });

You can check the following SO post.

like image 187
Hristo Eftimov Avatar answered Sep 27 '22 21:09

Hristo Eftimov


You have to declare the name of the function you want to use in your angular component, as-

declare var open: any;

This basically tells the compiler that open exists somewhere, which will be then found in your js file.

Also, to use the above method in your component, you will have to use this syntax-

anyCustomMethodName/anyLifeCycleMethod() {
    new open();
}
like image 33
Karan Hudia Avatar answered Sep 27 '22 22:09

Karan Hudia