To do load JavaScript files in a component, you have to do it manually inside the TypeScript file. Go into the app component TypeScript file and create a script element object. Then set the value of the src property to the path of the JavaScript file you want to load. This can be a URL or a local path in the project.
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.
As long as both are referenced by the web page, yes. You simply call the functions as if they are in the same JS file.
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...
You can either
import * as abc from './abc';
abc.xyz();
or
import { xyz } from './abc';
xyz()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With