2

In my component I have a foreach loop that is fired when a client is selected. Inside this loop I have to call a function in the same component.

To do this I must use this.functionName() to call the function. But obviously this will not work inside the foreach loop since 'this' is no longer the component itself.

Does anyone have a solution for this?

this.clientService.selectedClient.forEach(function(client) {
    this.getIntake(); // not working
});

1 Answer 1

8

Use arrow functions

this.clientService.selectedClient.forEach((client) => {
    this.getIntake(); // not working
});

otherwise this will not point to the local class instance

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Sign up to request clarification or add additional context in comments.

4 Comments

Such a simple solution! Thank you.
You can also pass the component as function scope: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions (See the lexical this part)
@brk, sure it will.
@MartineMulder - Don't forget to mark the answer as accepted (with the green check mark) if it solved your problem.

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.