How to Include a JavaScript Script File in Angular and Call a Function from That Script

How do I include a JavaScript script file in Angular and call a function from that script?

Refer the scripts inside the angular-cli.json (angular.json when using angular 6+) file.

"scripts": [
"../path"
];

then add in typings.d.ts (create this file in src if it does not already exist)

declare var variableName:any;

Import it in your file as

import * as variable from 'variableName';

How to call a method from a JS file into an Angular component

You should instantiate Columns object first, try this:

const columns = new Columns();
this.fetchedCols = columns.getAllColumns();

Columns object should be imported from a file where Columns is declared. But if you are using vscode or any other IDE you should be able to do that by hitting ctrl + space after Columns word

Calling function triggered by event from an external JS file in angular component

First, modify sample.js such that it exports fixedHeader like so

if (document.getElementById("fixedHeader")) {
window.onscroll = function () { fixedHeader(); };
var header = document.getElementById("fixedHeader");
var fixed = header.offsetTop;
}

export function fixedHeader() {
if (window.pageYOffset > fixed) {
header.classList.add("fixed-active-lob");
$('body').addClass("fixed-nav");
} else {
header.classList.remove("fixed-active-lob");
$('body').removeClass("fixed-nav");
}
}

With this adjustment, we've made sample.js into a module, with a single export named fixedHeader, and have thus enabled other modules, such as our current.component.ts, to consume it via the standard, explicit, and canonical method for sharing code in JavaScript: Modules.

Next, set "allowJs": true in your project's tsconfig.json, to inform TypeScript that our project includes a mix of both TypeScript and JavaScript source files.

Finally, import the fixedHeader function we've exported from sample.js directly into current.component.ts, remove the now redundant method from the Angular component class, and call the imported function as follows

 import {Component, HostListener} from '@angular/core';

import {fixedHeader} from '../assets/scripts/sample.js';

@Component({
// Angular boilerplate and ceremony
})
export class CurrentComponent { // or whatever it is actually called
@HostListener('window:scroll', ['$event'])
scrollHandler(event: Event) {
console.log("Scroll event", event);

fixedHeader();
}
}

Finally, remove the script tag that originally loaded sample.js from index.html.

Note: adjust import path above as needed based on the actual location of the files relative to one another.

Call a function of external js file in angular 5 component

Follow below steps in your component:-

1) First add a reference of your external JS file for importing it to the component. 
Import * as abcJS from '/YourExternalJS.js';

2) Now declare a "var" of the same name that your function has inside external JS.
declare var cartstack_updatecart: any;

3) ngOninit(){
cartstack_updatecart();
}

4) Do remember that your JQuery should be loaded first than your external JS file.

I have called that function on ngoninit lifecycleHook.
Also instead of declaring external JS file inside Index.html, I would rather suggest you to declare it in angular-cli.json file in scripts array.
All the best.

How to add an external JavaScript file to an Angular app?

Works with following code:

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
title = 'app';
loadScript(url) {
const body = <HTMLDivElement> document.body;
const script = document.createElement('script');
script.innerHTML = '';
script.src = url;
script.async = false;
script.defer = true;
body.appendChild(script);
}

ngOnInit() {
this.loadScript('../assets/scripts/index.js');
}

}

Using external js file in angular 6 component

I made a demo: https://codesandbox.io/s/4jw6rk1j1x , like so:

testfile.js

function testa() {}
testa.prototype.testMethod = function testMethod() {
console.log("hello");
};
var testmodule = new testa();

export { testmodule };

And in the main.ts

import { enableProdMode } from "@angular/core";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";

import { AppModule } from "./app/app.module";
import { environment } from "./environments/environment";

import { testmodule } from "./testfile";

testmodule.testMethod();

if (environment.production) {
enableProdMode();
}

platformBrowserDynamic()
.bootstrapModule(AppModule)
.catch(err => console.log(err));

You can see on the console tab the 'hello' text

Note that I made some changes in the testfile.js

How to call JavaScript functions from Typescript in Angular 5?

1. How and where to include JavaScript Files in Angular Project?

You need to include your JS file in the asset folder and refer this JS file in .angular-cli.json file.

Refer the snapshot's,

Folder structure should be like this.

Sample Image

.angular-cli.json

Sample Image

2. How to call the JavaScript Functions from Typescript class?

your TS should be like this.

Sample Image

myJsFile.js file content.

Sample Image

This sample logic mentioned above will work, I have tried and tested using version 4, So I am expecting it to work with version 5 also.

Updating the answer for the new Angular version release. Working
perfectly till version 11.2.6.

Find the code (function with parameter) here for Angular11



Related Topics



Leave a reply



Submit