Step-by-step guide on integrating a custom JS file into an Angular component

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.

Answer №1

To include the custom.js file, make sure to import it into the specific component where you intend to use it.

Answer №2

Incorporate an Angular service specifically designed to invoke the customTestHello1() function within your component following the successful importation of said service in the relevant component. Be sure to include the service in the providers array located in module.ts. For a comprehensive guide on creating services, please visit: https://angular.io/tutorial/toh-pt4

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating an unique identification code within the input field

I have a HTML code that displays geolocation information: <span id="currentLat"></span>, <span id="currentLon"></span> When combined with JavaScript, it works perfectly. However, I am trying to display the above value in a text fi ...

The functionality of async.series and async.each is not behaving as anticipated

I am currently working on developing a web scraping tool using nodeJS to extract image URLs from a website's HTML, store them in a cache, and then identify the largest image based on file size. However, I'm facing an issue where the function de ...

Tips for parsing data arrays in HTML templates

I have three variables and I created an array where I pushed all these three variables in. In my HTML template, I am using a table. I tried using *ngFor but it is not working, and also attempted string interpolation which also did not work. Currently, I ...

Implementing Facebook conversion tracking when there is no distinct 'Thank you' page can be done by utilizing the onclick event

Currently working on incorporating Facebook conversion tracking into a Facebook Tab. To see the page, visit this link. The issue I'm facing is that a separate page does not load after the form has been submitted. Is there a way to execute a section of ...

Using a combination of Javascript and PHP to dynamically update the innerHTML of multiple elements

I am working on updating the innerHTML of a webpage using Javascript after an onclick event. In my java.js file, I am utilizing this code to access a PHP page that echoes back the text for updating the innerHTML. The issue arises when attempting to update ...

Creating a simulation in THREE.js that incorporates MeshBasicMaterial, with the added feature of being able to

Creating a dungeon crawler game using three.js has been quite the learning experience. Initially, I opted for MeshBasicMaterial to ensure everything was uniformly visible in the dungeon. However, I wanted to experiment with adding bonus lights peeking thro ...

Testing an event within a subscription in Angular 4: A step-by-step guide

I am facing an issue with my component where I subscribe to an event in the constructor. To send an event, I use an event service: import {Injectable} from '@angular/core'; import {Observable} from "rxjs/Observable"; import {Subject} from "rxjs ...

Can you explain the distinction between Observable<ObservedValueOf<Type>> versus Observable<Type> in TypeScript?

While working on an Angular 2+ project in Typescript, I've noticed that my IDE is warning me about the return type of a function being either Observable<ObservedValueOf<Type>> or Observable<Type>. I tried looking up information abou ...

Modifying the content in one form field based on the information entered in another input field

I have a scheduling application that includes a form for selecting both the departure city and arrival city. The app is designed for international travel only, so when a user selects a city from Hungary as the departure city, I want to exclude all Hungaria ...

Utilizing AngularJS: Dynamically employ custom directives for enhanced reusability

I am currently developing my debut single page Angular.js application and finding myself in a bit of a rut when it comes to programmatically compiling/evaluating a custom directive to insert it into the DOM from within a controller. The custom directive I ...

Strategies for smoothly navigating the page to a specific div every time

Currently, I am working on a form that requires submitting multiple child forms. To enhance user experience, I have incorporated jQuery functionality to display a message at the top of the page upon each submission. Now, my goal is to implement a feature w ...

What is the best way to showcase JSON data on a webpage?

Currently, I have a total of 3 different objects containing education details in my JSON data. While I am able to display them in the console using a for loop, I am only able to show one object in my HTML output. How can I push all three details to my HTML ...

Combine multiple arrays in JavaScript into a single array

Here is the array I am working with: array = ['bla', ['ble', 'bli'], 'blo', ['blu']] I need to transform it into this format: array = ['bla', 'ble', 'bli', 'blo', &a ...

How to use jQuery to dynamically set the value of a column span in a

Struggling with setting the value for a table column span. Here is my jQuery code: $('tr td data-th=Name span').val('My span content...'); This is how my HTML appears: <tr> <td data-th="Name"><span class="edit-inpu ...

Make jQuery fire an event when the "enter" key is pressed

I'm trying to create an event that will trigger when the "enter" key is pressed. I've been using this code, but for some reason it's not working and I can't figure out why. After searching everywhere, I came across this snippet that see ...

Align content distributed evenly will not display a division

I am currently using React to code and learning by doing so. I have two different images displayed, each followed by a div element with a height of 20px and a brown background color. I have set the height to "100%" and justifyContent to "space-between", bu ...

Detecting property changes in Angular 2: A step-by-step guide

I've created a basic class structure like so: export class MessagesPage { @ViewChild(Content) content: Content; public message = ''; public messages = []; public state = 'general'; } Can I implement a way wit ...

What is the process of personalizing a DaisyUI theme in Tailwind with TypeScript?

I am trying to tailor an existing DaisyUI theme using my tailwind.config.ts file for my Next.js project. Although the DaisyUI documentation only provides examples in JavaScript (text), I want to customize it within my TypeScript environment. Below is a s ...

Changes made to the updated component fields are not reflecting on the user interface

I've encountered an issue where I can't seem to update a variable in a component that is being displayed on the UI. Even though the content of the variable changes correctly, the UI fails to reflect this change. Strangely enough, when checking th ...

Why is it that using e.preventDefault() does not prevent the link from being followed?

What is the solution to prevent a link from being followed with this specific event handler? http://jsfiddle.net/chovy/rsqH7/1/ <table> <tbody> <tr class="msg"> <header><a href="http://cn ...