Trying to grasp Angular, I embarked on adding some JavaScript logic to one of my components from a separate JS file. While following advice from a similar query (How to add custom js file to angular component like css file), it seems I missed something crucial. Can someone shed light on what might have gone wrong?
To experiment with different declarations, I created a file named custom.js
and saved it in the src/assets
folder:
(function customTestHello1() {
console.log("customTestHello1: Hello!!!");
alert('customTestHello1: Hello!!!');
})();
function customTestHello2() {
console.log("customTestHell2: Hello!!!");
alert('customTestHell2: Hello!!!');
}
I made sure to include this file in angular.json
:
"scripts": [ "src/assets/custom.js" ]
In my component's ts-file
, I added:
declare const customTestHello1: any;
declare const customTestHello2: any;
Then, within the ngOnInit
function of the component, I called these functions:
ngOnInit(): void {
customTestHello1();
//customTestHello2();
}
Upon inspecting my page, an error surfaced in the console:
ERROR ReferenceError: customTestHello1 is not defined
at MyComponent.ngOnInit (my.component.ts:20)
at callHook (core.js:3038)
at callHooks (core.js:3008)
at executeInitAndCheckHooks (core.js:2960)
at refreshView (core.js:7186)
at refreshEmbeddedViews (core.js:8279)
at refreshView (core.js:7195)
at refreshComponent (core.js:8325)
at refreshChildComponents (core.js:6964)
at refreshView (core.js:7221)
Even uncommenting "customTestHello2()" yielded the same result.
What am I missing here? How can I effectively integrate JS into an Angular project, specifically within a component?
If I incorporate the following snippet into my script:
window.initMethod = function() { console.log("customInitMethod: Hello!"); }
and add this line to myComponent.ts:
let initMethod: any;
then invoke it like so:
ngOnInit(): void {
initMethod();
//customTestHello1();
//customTestHello2();
}
An alternative error surfaces:
core.js:4197 ERROR TypeError: initMethod is not a function at MyComponent.ngOnInit (pingball.component.ts:21) at callHook (core.js:3038) at callHooks (core.js:3008) at executeInitAndCheckHooks (core.js:2960) at refreshView (core.js:7186) at refreshEmbeddedViews (core.js:8279) at refreshView (core.js:7195) at refreshComponent (core.js:8325) at refreshChildComponents (core.js:6964) at refreshView (core.js:7221)
Your guidance is much appreciated!
P.S. I would greatly benefit from recommendations on tutorials that offer up-to-date examples.