Getting access to a function within the same TypeScript file from another exported function in Angular

I'm having trouble accessing a function from another export function within the same TypeScript file. Can anyone help me with this?

app.component.ts:

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

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

  addingNumber(total:any){ 
   console.log(total);
  }
}

export function sum(a: number, b: number) {
  const num = a + b;
  this.addingNumber(num);
}

hello.component.ts:

import { sum } from './another-file';

sum(50, 10);

Demo : https://stackblitz.com/edit/angular-ivy-vewk4c?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fhello.component.ts,src%2Fapp%2Fapp.module.ts

Answer №1

To ensure your hello component works correctly, you must call the function within a specific function:

import { sum } from './app.component';

@Component({...})
export class HelloComponent {
   ngOnInit(): void {
     sum(1, 2);
   }
}

In addition, when working with the app component, you cannot access the addingNumber function externally without creating an instance of the AppComponent class.

@Component({...})
export class AppComponent implements OnInit {
  title = 'bus-poc';
  ngOnInit(): void {}

  addingNumber(total:any){ 
   console.log(total);
  }
}

export function sum(a: number, b: number) {
  const num = a + b;
  const appComponent = new AppComponent();
  
  appComponent.addingNumber(num);
}

If your AppComponent class requires any injected dependencies, they must be provided accordingly. The exact purpose of your code is unclear, but this structure demonstrates how to handle it.

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

Issue with TypeScript createProgram due to undefined 'ts.sys' error

I am encountering an issue while trying to utilize the createProgram function. The error message states that ts.sys is undefined when running the following code: try { createProgram(Utils.getFileNames(), { lib: ['lib.es6.d.ts'] ...

Angular PrimeNg carousel with personalized previous and next buttons

The information is provided in the image attached, with all CSS code available on stackblitz. I am looking to customize the Next and Prev buttons by having their borders match the inside boxes and be rounded. This will indicate to the user that there is a ...

Establish a new subpage that can have multiple main pages

I am currently working on implementing a navigation feature in an Angular application. I want to be able to access the same page from different "parent" pages while maintaining the navigation bar's awareness of the origin page. For navigation, I am u ...

The NgModel function within *ngFor is executing more times than necessary during initialization

Displayed on screen are a list of tutorials with check boxes next to each tutorial's states. These tutorials and states are pulled from the database, each tutorial containing a name and an array of associated states. Here is the HTML code: <div c ...

Guide to displaying a particular component depending on the URL in Angular 5

Currently, in group-summary.component.html, this code is used: <div class="row"> <ng-container> <nol-apple-details *ngIf="isAppleRouteActivated" [someDetails]="detailsToShow" class="col-xs-12 col-md-12"></nol-apple-detai ...

Combining string types with spaces and accepted types in TypeScript, potentially recursive

type AcceptedClass = "one" | "two" | "three"; type ClassNameType = `${AcceptedClass} ${ClassNameType}`; const className: ClassNameType = "one two three"; const className2: ClassNameType = "two one three one th ...

Export data from Angular Material data table to Excel format

I'm currently utilizing the angular material data table to showcase data in a tabular layout. I have a requirement to add a feature that enables the export of tabular data to an Excel sheet. Unfortunately, I haven't been able to locate any resour ...

What is the best way to preserve the "window history state" within the current URL?

I am looking to store the "window history state" within the current path, for instance {offset: 10}. This way, when I navigate to a different path and then return using location.back(), I can retrieve the previous path along with the stored state ({offse ...

Alert of incompatible browser in application developed using create-react-app

After developing a web application using create-react-app, I encountered the issue of unsupported browsers such as IE10. Users with older browsers need to be notified to switch to a more up-to-date one for optimal performance. I find myself in a predicame ...

Creating an exit button in Ionic 4 Cordova is a simple process that can be achieved with

I've been attempting to implement an exit button on Ionic 4 with Cordova, but none of the solutions have been successful so far. If anyone has insights on the correct approach to achieve this, I would greatly appreciate any guidance. Many thanks in a ...

Implementing Dynamic FormControl Values within FormGroup in Angular: A Step-by-Step Guide

GenerateFields(customControl, customValue): FormGroup { return this.fb.group({ customControl: new FormControl(customValue), }) } I am looking for a way to dynamically add the value of customControl from the parameter passed in the Ge ...

When retrieving data from MongoDB, an error occurs stating "Unable to read the property 'firstname' of null."

I've been working on retrieving user information from MongoDB and displaying it through HTML, but I keep encountering an error that says: "Cannot read property 'firstname' of null." For my backend service, I'm using Express and Node.js, ...

In Angular 17, is there a way to trigger a component's method when a Signal is modified?

Our component is designed to monitor signals from a Service: export class PaginationComponent { private readonly pageSize = this.listService.pageSize.asReadonly(); private readonly totalCount = this.listService.totalCount.asReadonly(); readonly pag ...

What is the best way to assign a value to a class variable within a method by referencing the 'this' keyword?

Is there a way to set the state of this Ionic react app when displaying the outcome of a reset service? I am facing challenges with using this.setState({resetSuccess}) within a method due to scope issues. (Details provided in comments) Here is the relevan ...

Leveraging the 'ref' keyword in TypeScript with Next.js

Currently, I am learning TypeScript in React but encountered a warning. import {useref} from 'react' export default function test(){ cons tmp = useRef() const data = tmp.current?.value return ( <div> <input type = ...

Generic partial application fails type checking when passing a varargs function argument

Here is a combinator I've developed that converts a function with multiple arguments into one that can be partially applied: type Tuple = any[]; const partial = <A extends Tuple, B extends Tuple, C> (f: (...args: (A & B)[]) => C, ...a ...

Exporting External JavaScript Variables in Angular 2 Using Typescript

In my Configuration JS file, I have defined some configuration variables. For example: var config = {url:"xyz.com"}; I need to access these configuration parameters throughout my application. I attempted to export the config variables like this: export ...

Having trouble with the SELECT functionality in Angular2/4 and SAFARI?

Having a major issue with the basic html SELECT component on SAFARI. Here is the code snippet: Initial Declaration idFamily:any = null; listProductFamily: ProductFamily[]; Loading listProductFamily this.productFamilyService.GetAll().subscribe( ...

What is the best way to make Angular Material Fields fill 100% of the container width?

Can you help me figure out how to adjust form fields to maximum width on a screen size less than 840px? I'm currently using Angular, Angular Materials and Flex-Layout. I'm having trouble with making this CSS code work properly. Can you explain ...

The number entered will be incorporated into the API URL key value by passing the variable from page.html to services.ts

Recently diving into the world of Ionic, Angular, and Typescript, I've had a burning question. Can the number inputted be added to the API URL as one of the key values? I came across this helpful guide, specifically focusing on key event filtering (wi ...