1

I got a function name and want to call it inside Angular class (.ts file). eval() is not an option.

I have tried using window[functionName] , but it fails, guess because window context is outside the class

Any idea?

2
  • 1
    can you please provide more details on the component? Commented Dec 24, 2019 at 8:56
  • whats the error when it fails? Commented Dec 24, 2019 at 9:48

2 Answers 2

1

It's pretty easy. For an example getData is your function name.

getData() {
  // your code goes here...
}

functionName = 'getData'; // function name as a string

Now you can call this function like below:

this[functionName]();
Sign up to request clarification or add additional context in comments.

Comments

0

If your function is defined in a seperate class or service import it via the constructor and invoke the function. Like this

constructor(private serv: FunctionService){
   serv.your_function();
}

Call it inside the constructor or where ever it is appropriate depending on the context. Hope this sounds meaningful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.