How To Use Methods From External Js In Angular
I need to call a function from external js file into my Angular component I already go through the related question How can i import external js file in Angular 5? How to include
Solution 1:
You can follow this below steps
1) First add a reference of your external JS file for importing it to the component.
import * as wrapperMethods from'../../src/assets/external.js';
2) Nowdeclare a "var"of the same name that your function has inside external JS.
declarevarwrapperMethods: any;
3) ngOninit(){
wrapperMethods();
}
Solution 2:
put your external .js file under scripts in build
if still can not see methods inside it put in in index.html
<scriptsrc="assets/PATH_TO_YOUR_JS_FILE"></script>
in your component after import section
declare var FUNCTION_NAME: any;
ANY_FUNCTION() {
FUNCTION_NAME(params);
}
Solution 3:
Don't get confused with typings.d.ts
. Follow below steps.
1.Add your external file inside assets
folder. The content of this file will be by default included as per your angular-cli.json
.
2.The function of your js which you're going to use must be exported
. i.e.
exportfunctionhello() {
console.log('hi');
}
3.Import your file inside your component as below.
import * as ext from'../assets/some-external.js';
4.Now you can reference it like
ext.hello();
Solution 4:
Steps:-
1. create a external js file.
2.In component.ts use the below code.
ngOnInit() {
this.loadJsFile(JsFilePath);
}
publicloadJsFile(url) {
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
}
3.If u use jquery then define selector in html to render. Or store data in variable.
- Make sure you have to add jquery cdn in index.html and you have to install Jquery and its types package from npm.
Post a Comment for "How To Use Methods From External Js In Angular"