What is the process of invoking an external JavaScript function in Angular 5?

I recently downloaded a theme from this source. I need to specify script and CSS in the index.html file.

The body section of index.html looks like this:

<body>
  <app-root></app-root>
  <script type="text/javascript" src="./assets/js/main.85741bff.js"></script>
  <script type="text/javascript" src="./assets/js/common.js"></script>
</body>

In common.js, I have defined my function and called it from main.85741bff.js file.

This is the function in common.js:

document.addEventListener("DOMContentLoaded", function (event) {
     masonryBuild();
     navbarToggleSidebar();
     navActivePage();
});

However, I am facing an issue where I can call the function when the page reloads but not when the content loads dynamically.

If anyone has any suggestions on how to resolve this problem, your help would be greatly appreciated.

Answer №1

You have the ability to incorporate javascript within your Angular application.

Begin by following these steps:

Step 1. Create a demo.js file in the assets/javascript directory.

export function test1(){
    console.log('Executing test 1 function');
}

Step 2. Create a demo.d.ts file in the assets/javascript folder.

export declare function test1();

Step 3. Implement it within your component

import { test1 } from '../assets/javascript/demo'; 
 @Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() {
    console.log(test1());
  }
}

Please ensure that both the .js and .d.ts files have the same name.

Answer №2

To resolve the issue, make sure to adjust the sequence in which your JavaScript files are loaded. It is advisable to load common.js before main......js. This way, your script will be able to access functions from files that have already been loaded. Simply swap the order of these two lines of code:

<body>
  <app-root></app-root>
  <script type="text/javascript" src="./assets/js/common.js"></script>
  <script type="text/javascript" src="./assets/js/main.85741bff.js">/script>
</body>

Answer №3

When working on an Angular 4 or 5 project, you'll come across the .angular-cli.json file in the project folder.

Within this file, there is a section that looks like this:

"apps": [
  {
    "scripts": []
  }
]

To include external JavaScript files in your project, simply add the path to your script within the "scripts" array.

Answer №4

To access these functions, you can utilize the window object:

document.addEventListener("DOMContentLoaded", function (event) {
      window['toggleSidebar']();
      window['activatePage']();
 });

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

Fade-in a new, revised text after fading-out the original text in ReactJS

I have a bunch of p elements that I'd like to cycle through, fading in one at a time and then replacing it with the next. Here is the jQuery example on CodePen: https://codepen.io/motion333/pen/EBBGVM Now, I'm attempting to achieve the same effe ...

What is the alternative to using toPromise() when utilizing await with an Observable?

This website mentions that "toPromise is now deprecated! (RxJS 5.5+)", however, I have been utilizing it recently with AngularFire2 (specifically when only one result is needed) in the following manner: const bar = await this.afs.doc(`documentPath`).value ...

What are the steps to kick off my React App once I've cloned it?

Currently grappling with deploying my app using Netlify, I encountered an issue after cloning the app onto my new computer. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8afee5eee5e6e3f9fefcb8cabba4baa4ba">[email  ...

Guide on merging non-modular JavaScript files into a single file with webpack

I am trying to bundle a non-modular JS file that uses jQuery and registers a method on $.fn. This JS must be placed behind jQuery after bundling. Here is an example of the structure of this JS file: (function($){ $.fn.splitPane = ... }(JQuery) If y ...

What is the best approach for creating a test that can simulate and manage errors during JSON parsing in a Node.js

My approach to testing involves retrieving JSON data from a file and parsing it in my test.js file. The code snippet below demonstrates how I achieve this: var data; before(function(done) { data = JSON.parse(fs.readFileSync(process.cwd() + '/p ...

Learn how to trigger an event or API call in Angular 8 when the browser is closed with the help of HostListener

I am facing the challenge of calling a simple websocket closure API when the browser is closed in my project. I attempted to utilize HostListener, but unfortunately it did not work as expected. You can find the code snippet below: https://stackblitz.com/ ...

What is the best way to refine React Component's props with Typescript?

My setup involves utilizing two specific components: Test and Subtest. The main functionality of the Test component is to provide visual enhancements and pass a portion of its props down to the Subtest component. Some props in the Subtest component are des ...

Puppeteer: Easier method for managing new pages opened by clicking a[target="_blank"]; pause for loading and incorporate timeout controls

Overview I'm seeking a more streamlined approach to managing link clicks that open new pages (such as target="_blank" anchor tags). By "handle," I mean: fetch the new page object wait for the new tab to load (with specified timeout) Steps to r ...

Reaching the maximum request threshold

Currently, I am facing an issue where users are able to upload files from the client side (using Angular 4) to the server (implemented with Spring Boot). The problem arises when a user attempts to upload more than 6 files at once. In such cases, Chrome uti ...

Tips for creating multiple files using nodejs and express

I am currently working on developing a personalized code editor that consists of 3 textareas: html, css, and javascript. The objective is to save the data from each textarea into individual files. With the help of express and nodejs, I have successfully m ...

Typescript: parameter must be included if another is also required

In the user interface, the parameter c is mandatory only if the parameter a is set to true. interface IArguments { a: boolean, b: string, c: string } The solution below seems to be effective, but how can I exclude the c parameter in the first scenar ...

Ways to display pictures by invoking an API within the antd item list container

Upon page load, I am fetching images from a database using an API. Now, my goal is to display these images within a Modal in Antd. How can I accomplish this with the code snippet below? const MyVehiclePage = (props) => { useEffect(() => { co ...

The Mat table is not updating on its own

I am facing an issue in my Angular application where a component fetches a hardcoded list from a service and subscribes to an observable to update the list dynamically. The problem arises when I delete an element from the list, as it does not automaticall ...

Adding a new element with Jquery when a dropdown option is selected

What is causing this issue to not function properly? <script> $(document).ready(function(){ $('#custom_field option').click(function(){ $('#custom_field_input').append('<tr><td></td> ...

Angular Universal experiences issues with route functionality after page reloads

Recently deployed an Angular Universal web app on Firebase. While all routes within the application are functioning properly, encountering errors when trying to access them externally. Below is the error message: functions: Starting execution of "ssr" ⚠ ...

Tips for preventing hcaptcha from displaying image challenges during web scraping with puppeteer

When I attempt to scrape a website, the process of passing the captcha can be unpredictable. Sometimes, after clicking on the captcha checkmark, I am presented with images to solve the captcha. Other times, it simply passes me through without any further a ...

Error encountered while sending a post request from Angular to NodeJS with JSON data

When making a POST request to a NodeJS app from Angular, the request code in Angular is as follows: export class SearchComponent { constructor(private http: HttpClient) {} newWord = ''; keyword = ''; onClick() { const head ...

jquery mobile popup message will fade away within a short time interval

In my main page, I have the following code: $(document).bind("pageinit", function () { $.mobile.loading('hide'); }); I am displaying a popup message using the following code: $.mobile.loading('show&apos ...

Is there a way to make an angular component reuse itself within its own code?

I am dealing with a parent and child component scenario where I need to pass data from the parent component to the child component. The aim is to display parentData.name in the child component when parentData.isFolder===false, and if parentData.isFolder=== ...

Attempting to use vue-test-utils-getting-started with the standard configuration results in a "Preset Not Found" error during

Currently, I am in the process of conducting a unit test by referring to the official guide provided. To do so, I have cloned the demonstration repository named vue-test-utils-getting-started. To replicate the issue, follow these steps: After cloning vu ...