What is the method for reaching a function in TypeScript?

I am currently working on a hybrid app using Typescript and I have been trying to figure out how to access a function in Typescript.

Here is an example of my code:

export class SuccessPage {
 public removeRoom(){
    console.log("removeroom");
 }
}
function getRoom(){
  var searchList = '';
  ....
  searchList += '   <li id=\'' + result.Item[0].room_num + '\'>';
  searchList += result.Item[i].dest_x + ', ' + result.Item[0].dest_y + 
               '<br><button class="removeRoom" onclick="removeRoom()"> </button></li>';
  ....
 }

I am looking for a way to access the removeRoom function. Can anyone guide me on how I can achieve this?

Answer №1

It appears that the current architecture may not be optimal (more details on this later), but to address your query, there are two possible approaches:

  1. You can maintain the removeRoom method as is and utilize it in another location by instantiating the SuccessPage class, like so:

    const page = new SuccessPage();
    page.removeRoom();
    
  2. Alternatively, you could make the removeRoom method static and access it without creating an instance:

    static removeRoom() {...} 
    
    /* ... *./
    
    SuccessPage.removeRoom()
    

    (Please note that making a method static is only advisable if it does not rely on instance fields such as this.something or this.doSomething() within).

Now, regarding the "architecture" issue. If the removeRoom method does not require references to the class instance and needs to be accessed from multiple locations, it might be more efficient to define it independently - either as a standalone utility function (to be used directly in both the component and JavaScript code) or as part of an Angular service (wherein you would need to create an instance of the service to use it outside the Angular component in JavaScript code)

Answer №2

When you bring the class into a different file, you have the ability to utilize the function using this method:

import SuccessPage from './SuccessPage';

const newPage = new SuccessPage()
newPage.removeRoom()

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

There seems to be an issue with locating a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables like Arrays

My route.js const express = require('express'); const router = express.Router(); const University = require('../models/university'); var mongo = require('mongodb').MongoClient; var assert = require('assert'); va ...

Tips for successfully sending properties from a parent component to a child component in a TypeScript and React application

I am trying to achieve prop passing from a parent component to a child component in React using TypeScript. However, I am unsure how to properly define these props in the type. Below is the code snippet: function Parent() { ...

Creating validation for an autosave reactive form in Angular 2: A step-by-step guide

Seeking advice on implementing an autosave feature for a reactive Angular 2 form. The idea is that as the user types in values, the form should automatically save if the input is valid. Below is the code snippet: export class BusinessFoundationsPage { ...

The issue encountered during the construction of the nrwl library project is that object Object is not recognized as a PostCSS

We are currently facing an issue with our nrwl-nx workspace library project (based on Angular 8) that contains 3-4 angular libraries. While the ng serve function works properly, we have started encountering errors when trying to run ng build my-lib. On ou ...

How can dependencies for an entire class or module be mocked in the mocha ecosystem similar to jest.mock?

I am currently working on unit testing a module that resembles the following code structure: import { Countdown } from "./database/orm"; export class PersistentTimer { protected constructor(...) { ... } // To ensure database writing ...

How to Delete an Item from an Array in BehaviorSubject Using Angular/Typescript

I have encountered an issue while trying to delete a specific element from my array upon user click. Instead of removing the intended item only, it deletes all elements in the array. I attempted to use splice method on the dataService object, but I'm ...

Breaking down code with Webpack for future extensibility

We are in the process of developing a game and have successfully implemented code-splitting to separate vendor libraries and the core engine into individual bundles, as well as splitting levels into separate bundles. As we plan for future releases where t ...

What is the best way to make mouse and touch events trigger responses in Angular versions 9 and above?

I've been searching high and low for a library or tried-and-true method to handle common user events reactively, but unfortunately my quest has come up empty. After some digging, I stumbled upon what seemed like a solid solution: https://github.com/t ...

Creating an Angular 2 project using Maven

Can anyone guide me on how to create an angular2 typescript project with maven? Is there a way to include npm install or ng build commands in the pom.xml file for building the project efficiently? ...

Discovering a variable within an enzyme wrapper for the locate function

Struggling through testing with jest + enzyme. I have an array called OptionsArray that contains options mapped to buttons in a component. In my testing suite for the component, I attempted to do the following: import React from 'react'; import { ...

Issue with react-native-svg ForeignObject missing in project (React Native with Expo using TypeScript)

I am working on a React Native project in Expo and have incorporated the expo TypeScript configuration. Using "expo install," I added react-native-svg version 9.13.3 to my project. However, every time I attempt to render the SVG using react-native-svg, I ...

Tips for positioning your side navigation menu parallel to the page edge

Im looking to have the side navigation floated to the left as I scroll down the page. I tried using the sticky property, but it didn't work out. Here's a snippet of the code: .sticky-class { position: sticky; top: 30px; } This is how my HTML ...

Modify the appearance of a specific date using ng-pick-datetime

Currently, I am incorporating the Angular Date Time Picker into my frontend design. On the backend, there is a method that determines all the dates that are unavailable for a particular user. I am looking to adjust the color on the calendar to highlight t ...

Retrieving the status of a checkbox using Angular's field binding feature

While using Angular 5.1.1, I am facing an issue where a function is not called correctly when a checkbox changes. This problem seems to occur specifically with the checkbox input type, as it always sends the value "on" to the function even when the checkbo ...

Navigating the JQueryUI Sortable Feature with TypeScript

Using the JQueryUI Sortable (version 1.12.1) method in a TypeScript (version 3.2.1) environment has mostly been smooth sailing for me. However, I've hit a roadblock while trying to implement the Sortable Widget's helper option. Here's a snip ...

Tips for Successfully Transmitting Information via Mat-Dialog

Having trouble passing data from a dialog back to the parent component. Specifically, I'm struggling with updating the value of an array in the `afterClosed` function. I've tried using `patchValue` and `setValue`, but it doesn't seem to be w ...

What is the best way to divide a range of numbers between m and n using JavaScript

Struggling with the Angular slice pipe when working with an observable fetching data. Although not a difficult task, I'm facing confusion. Check out my example below: value$: Observable<number[]>; // Fetches an array like [1, 2, 3, 4, 5, 6, 7, 8 ...

What sets apart `const [a, b, c] = array;` from `const {a, b, c} = array;`?

let [x, y, z] = arr; let {x, y, z} = obj; Q: Can you explain the distinction between these two declarations? ...

Following the execution of the ng build command, an error occurred stating 'entry not found'

After successfully building my project using the command "ng build --prod" or "ng build --prod --base-href ./", and running it on a web server without any issues, I encountered an error whenever I refreshed the page (F5). The error message appears as shown ...

Having trouble locating the name 'user' in TypeScript?

I am puzzled by the Error that I am getting, especially since other components work fine without any issues. Could the problem lie with the TypeScript interface? Details.tsx import React, { FC } from "react"; import App f ...