Home > Mobile >  How to access function in the same typescript file from another export function in angular
How to access function in the same typescript file from another export function in angular

Time:06-20

I am trying to access a function from another export function in the same ts file. But not working. So, How to do it?

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/app/app.component.ts,src/app/hello.component.ts,src/app/app.module.ts

CodePudding user response:

In your hello component, you need to make that call within a function:

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

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

And then, in your app component, you cannot use the addingNumber function from outside, unless you instantiate the class AppComponent.

@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 has some dependencies injected, you will need to provide them. Not sure what logic you're trying to achieve but this is how you would do it.

  • Related