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.