How do I include a JavaScript script file in Angular and call a function from that script?
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';
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.
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...