Angular4 how to call a function in external js
I have a jscript that displays a log on the console:
x.js contains
function open() {
console.log('this a function');
}
in the index.html of my application
<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 am getting @
Initial exception: xJS is not defined
How can I call this external function?
source to share
Importing your file like this <script src="x.js"></script>
won't work.
You need to import it like this:
import * as xJS from './x.js';
If that doesn't work, an 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 .
source to share
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
there is somewhere to be found in your file js
.
Also, in order to use the above method in your component, you will have to use this syntax -
anyCustomMethodName/anyLifeCycleMethod() {
new open();
}
source to share