How to add JavaScript file in Angular project


In this tutorial, we are going to show how to add an external JavaScript (.js) file in the Angular project. Sometimes it’s required to add an external file to perform some task and in Angular project, an external file can not be added directly.

For example, you wanna show some alert messages when the page gets loaded through your JavaScript file. In Angular, it can be added in two ways:

Let’s see you have created a nand.js file which conation a function name().

nand.js
function name(){
  alert("I am Lucifer");
}

Solution 1

Step 1: Create a js named directory inside the assets directory and put the JavaScript (nand.js) file inside it.

How to add JavaScript file in Angular project

Step 2: Open the index.html and add a script tag to add the JavaScript file.

<script src="assets/js/nand.js"></script>

Step 3: Open the component where you want to use this JS file.

Add below line to declare a variable:

declare var name: any;

Use below line to call the function:

new name();
app.component.ts
import { Component, OnInit } from '@angular/core';

declare var name: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  
  ngOnInit(): void {
    new name();
  }
  
  title = 'app-js';
}

Solution 2

Step 1: Repeat Steps 1 & 2 already discussed in the above solution.

Step 2: Open the angular.json and add the JS file path in the “scripts” array.

How to add JavaScript file in Angular project

Step 3: Open the component where you want to use this JS file.

Add below line to declare a variable:

declare var name: any;

Use below line to call the function:

new name();
app.component.ts
import { Component, OnInit } from '@angular/core';

declare var name: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  
  ngOnInit(): void {
    new name();
  }
  
  title = 'app-js';
}

Test the application

“Voila”, now run your application and test. As soon as the application load it will open an alert box saying “I am Lucifer”.

References

  1. Adding CSS and JavaScript to an Angular CLI Project
  2. Data Binding in Angular

Similar Posts

About the Author

Manish Fartiyal
Hi!, I'm Manish Fartiyal, a full-stack web application developer. I love Java and other open-source technology, currently working at one of the top MNC in India. Read all published posts by Manish Fartiyal.