Timar Ivo Batis
Timar Ivo Batis

Reputation: 1996

Callback function passed in Angular template has no access to component

The callback function doesn't have access to anything in the component. I assume i have to bind "this" but im a bit lost on where i would do that. https://stackblitz.com/edit/angular-tzv5nl

In my html template i have a button where i pass a callback function as argument:

<button (click)="primaryAction('test',furtherAction1)">Action<button>

In my component i have the functions

primaryAction(string,callback){
this.primaryActionDone = "Done";
callback()
}

furtherAction1(){
alert("furtherAction1 called but has no access to 'this'");
this.furtherAction1Done= "Done"; //Error: Cannot set property 'furtherAction1Done' of undefined
this.furtherAction2()
}

furtherAction2(){
this.furtherAction2Done= "Done";
}

furtherAction1 has no access to this.furtherAction1Done or this.furtherAction2().
Now how would i go about having the proper "this" within the callback functions?

Upvotes: 1

Views: 2100

Answers (1)

user4676340
user4676340

Reputation:

This is just a scope issue.

To re-bind a context to a function, use call

primaryAction(string,callback){
  this.primaryActionDone = "Done";
  callback.call(this)
}

Upvotes: 2

Related Questions