Home > Software engineering >  How can I call a function defined in an Angular component in a JavaScript file?
How can I call a function defined in an Angular component in a JavaScript file?

Time:02-25

In a .ts file, I have the following code

export class SomeClass {
    .
    .
    .
    public someMethod() {
        ...
    }
}

I want to call this someMethod method in a .js file.

I tried

import { SomeClass } from '../../../../SomeClass';
.
.
.
SomeClass.someMethod();

but got the following error:

someMethod is not a function

Do I have to make the method static?

I prefer not because it calls other methods and I will have to make all of them static.

Can I create an instance of this class in the .js file?

Thanks!

CodePudding user response:

possible way

u can build your ts files using build command and convert it to javascript then call it in your js file

this should work

CodePudding user response:

there are two solutions either create instance of the class first then use public method like

let class = new SomeClass();
class.someMethod();

or make it static Method then your code will compile successfully

CodePudding user response:

Futhermore create a instance of the class, you can also use some like

export function MyClass() {
    return new SomeClass()
}

Or if you neeed a constructor

export function MyClass(args) {
    return new SomeClass(args)
}
class SomeClass{
   constructor(arg){this._arg=arg}
}

You can in .ts

import { MyClass} from '...';

@Component({
   ...
})
export class AppComponent {
  MyClass=MyClass //<--if you want to use in .html
  ....
  myfunction(){
     MyClass.someMethod();
     //or
     const obj=MyClass();
     obj.someMethod();
  }
}

You can also, if only defined functions use a const

export const Utils{
    someFunction:()=>{console.log("hello"}
}

And then you use simply Utils.someFunction()

  • Related