Adding, Loading, and Using JavaScript in Angular

Codeible
3 min readSep 26, 2022

--

Learn how to load and use JavaScript code inside your Angular project

Follow on Twitter: Codeible (@codeible) / Twitter.

View article on Codeible.com.

Hello, in this tutorial, you will learn how to load and use JavaScript code inside your Angular project.

Adding JavaScript files to your project

To add JavaScript files, locate the files on your computer and place them inside the assets folder of the project.

Copying JavaScript Files to Angular Project

Next, open the angular.json file and locate the scripts property inside.

Angular.json scrips property

In here, place the path of each JavaScript file you want to load into the array.

You can right click on the file in the explorer pane to get the path of the document and paste each path inside the array.

Remember to change the backward slashes into forward slashes.

"scripts": [   "src/assets/ExampleJS1.js"]

The assets folder is inside the src folder so we do “src/assets/” and the name of our file.

When we run our app, it will load and execute the code in JavaScript files.

Here is what is inside the ExampleJS1.js file:

function greet(){   alert("Hello");}alert("Pop up");

Result:

Results from JS file

Using Functions in the JS File

To use the functions or variables in the JavaScript files, declare a reference in a TypeScript file by typing declare and then the variable or function you want to reference.

import { Component } from '..'declare function greet(): void;@Component({   ....})export class AppCompoent {}

Then call it in the code.

import { Component } from '..'declare function greet(): void;@Component({....})export class AppCompoent {   constructor(){      greet();   }}

Using CDNs

If you have a CDN or a link to an online repository for the JavaScript file, you can just put script tags in the index.html page to load your files.

<!doctype html><html lang="en"><head>   <script src="..."></script></head><body><app-root></app-root></body></html>

However, you cannot add script elements in the html page of your components.

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.

Lastly, add the script element to the body of the HTML page.

import { Component } from '..'declare function greet(): void;@Component({   ....})export class AppCompoent {myScriptElement: HTMLScriptElement;   constructor(){      greet();      this.myScriptElement = document.createElement("script");      this.myScriptElement.src = ".....";      document.body.appendChild(this.myScriptElement);   }}

Recommended:

Download and try a New Auto Clicker / Click Assistant app in Google Play Store:

Loop Clicker — Apps on Google Play

Loop Clicker
Thumbnail

--

--