Using Angular 2 with Typescript to call a JavaScript function

How can I correctly invoke a JavaScript function from a component in Angular 2 (TypeScript)?

Below is the code for my component:

import { ElementRef, AfterViewInit }       from '@angular/core';

export class AppComponent implements AfterViewInit {

    constructor(private _elementRef: ElementRef) {
    }

    ngAfterViewInit() {
        /**
         * Works but I get the following error:
         * src/app.component.ts(68,9): error TS2304: Cannot find name 'MYTHEME'.
         * src/app.component.ts(69,9): error TS2304: Cannot find name 'MYTHEME'.
         */
        MYTHEME.documentOnLoad.init(); 
        MYTHEME.documentOnReady.init();

        /**
         * Works without error, but doesn't seem like the correct approach
         */
        var s = document.createElement("script");
        s.text = "MYTHEME.documentOnLoad.init(); MYTHEME.documentOnReady.init();";
        this._elementRef.nativeElement.appendChild(s);
    }
}

Directly calling the JavaScript function results in a compilation error, but the syntax in the "compiled" JavaScript file (app.component.js) is correct:

AppComponent.prototype.ngAfterViewInit = function () {
    MYTHEME.documentOnLoad.init();
    MYTHEME.documentOnReady.init();
};

The second way (appendChild) works without error, but it may not be the best way to go about it.

I came across this post about using a JavaScript function from TypeScript: Using a Javascript Function from Typescript. I tried declaring the interface:

interface MYTHEME {
    documentOnLoad: Function;
    documentOnReady: Function;
}

However, TypeScript doesn't seem to recognize it (no error in the interface declaration).

Thank you

Edit:

After following the advice from Juan Mendes, this is the updated code:

import { AfterViewInit }       from '@angular/core';

interface MYTHEME {
    documentOnLoad: INIT;
    documentOnReady: INIT;
}
interface INIT {
    init: Function;
}
declare var MYTHEME: MYTHEME;

export class AppComponent implements AfterViewInit {

    constructor() {
    }

    ngAfterViewInit() {
        MYTHEME.documentOnLoad.init(); 
        MYTHEME.documentOnReady.init();
    }
}

Answer №1

If you need to inform TypeScript about external (JavaScript) declarations, use the keyword declare. For more information, refer to https://www.typescriptlang.org/docs/handbook/writing-declaration-files.html

interface CustomTheme {
    documentOnLoad: Function;
    documentOnReady: Function;
}
declare var CUSTOM_THEME: CustomTheme;

Alternatively, you can declare it anonymously

declare var CUSTOM_THEME: {documentOnLoad: Function, documentOnReady: Function};

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

Passing data into a different controller

In the process of building a system that involves selecting elements from a list and viewing their details, I have encountered an issue while using MEAN stack. My goal is to pass the id of the selected element to the controller of the second page. However, ...

Form a tree structure using a compressed object

I’m struggling with a specific issue: I have an object structured like this: Object { id: string; parentId: string; } What I’m aiming for is a nested object structure like this: NestedObject { id: string; parentId: string; children: [ { ...

Filter JSON data in AngularJS ng-repeat by a specific ID

I'm having difficulty getting this to function properly. I've been attempting to filter a JSON file by specific ID and then iterate using ng-repeat. Here's what I have tried: This is the button trigger: <a href="#/compare-details">& ...

Tips for filling in the values for the options in a select dropdown menu

Currently, I am facing a strange bug related to the select element. Whenever I open the dropdown, there is always a mysterious black option at the top. This is how my HTML looks like: This particular element is part of my test controller. <select ng- ...

What is the proper way to add an object to an array within an object in TypeScript?

import {Schedule} from './schedule.model'; export class ScheduleService{ private schedules:Schedule[]=[ new Schedule("5:00","reading"), new Schedule("6:00","writing"), new Schedule("7:00","cleaning") ]; getSchedule(){ ret ...

Dynamic styling updates on page refresh in Next.js

There is a strange issue with my styling that I can't seem to figure out. I have a NavBar set to be 20vh in height and an image set to be 100% in width. However, whenever I refresh the page, the NavBar height decreases and the image width increases si ...

Using Typescript to pass an optional parameter in a function

In my request function, I have the ability to accept a parameter for filtering, which is optional. An example of passing something to my function would be: myFunc({id: 123}) Within the function itself, I've implemented this constructor: const myFunc ...

Create a class for the grandparent element

Is there a way to dynamically add a class to a dropdown menu item when a specific child element is clicked? Here's the HTML structure I have: <ul id="FirstLevel"> <li><a href="#">FirstLevel</a></li> <li>< ...

Utilizing Nuxt3's auto-import feature alongside Eslint

I'm having trouble finding an eslint setup that is compatible with Nuxt3's auto-import feature to prevent no-undef errors. I have tried various packages like @antfu/eslint-config, plugin:nuxt/recommended, @nuxt/eslint-config, @nuxtjs/eslint-confi ...

Having trouble compiling for IOS using a bare Expo app? You may encounter an error message that reads "Build input file cannot be found."

Encountering Error When Running react-native run-ios on Bare Expo App I am experiencing an issue while trying to run the 'react-native run-ios' command on my Bare expo app. The error message I am receiving is: "Build input file cannot be found: ...

What is the best way to update a CSS class in React JS?

Suppose I have a CSS class called 'track-your-order' in my stylesheet. Whenever a specific event occurs, I need to modify the properties of this class and apply the updated values to the same div without toggling it. The goal is to replace the ex ...

The concept of nested ng-repeat in AngularJS

My HTML structure is as follows: <div class="fields-plan"data-ng-repeat="roomname in assign.roomname"> <section> <span>Room: {{roomname}}</span> </section> <ul data-ng-repeat="r ...

React does not trigger a re-render when dynamically generated buttons are created

I am encountering an issue with displaying social media buttons on my website. I have implemented a tweet button and a Facebook like button to appear on every page, but they only load correctly on the initial page visit. Upon navigating to another page and ...

What is the best way to load the contents of an HTML file into a <div> element without it behaving as an object?

Currently, I am importing an HTML file into a <div> in this manner: function load_content() { document.getElementById('content').innerHTML = '<object type="text/html" width="100%" height="100%" data="./content.html"></obj ...

jQuery Datatables causing hyperlinks to malfunction on webpage

After implementing jQuery datatables on this example using a PHP serverside processing file pulling data from MySQL, the Sign-in button used to work but now it just reloads the same index page. Manually typing in the address linked to the Sign In page work ...

I have been utilizing ESBuild to compile JavaScript code for browser usage. However, I encountered an issue when trying to import CSS as I received an error message stating "Unexpected '.'". Can anyone provide guidance on how to resolve this issue?

I am currently developing a JavaScript notebook that operates within the browser environment. To compile my code, I have chosen to utilize ESBuild. My primary objective is to enable the handling of CSS imports such as <import 'bulma/css/bulma.css&a ...

Ways to extract a return from an Observable

Do you know how to retrieve the _value from the following code snippet: Here is the function I am referring to: jobsLength(){ const jobslength:any; jobslength=this.searchLogic.items$ console.log(jobslength) }; ...

How can I update the color of table rows after the ng-repeat has been implemented?

My current project involves Django, Python, and a bit of AngularJS. I have a dynamic history table that grows as data is added. I am looking to apply some simple CSS to this table - specifically, I want to give every even-numbered row a black background ...

Having trouble finding the element within the form tag even after attempting to use .switchTo().defaultContent()

My HTML is structured like this: <section> <div> <form> <div>Username field</div> <div>Password field</div> <div> <div>.. <div>.. <iframe& ...

Using Python to interact with forms and click JavaScript buttons

Is there a way to automate form filling on a website by setting specific parameters that will bring up products matching those parameters? I attempted to use mechanize in python, but it does not support javascript. It seems like the process of entering par ...