Home > OS >  Preserving this context when passing a callback function via Angular template
Preserving this context when passing a callback function via Angular template

Time:10-08

My component defines a method that receive a callback as a parameter

  sendDeleteRequest(btn: MatButton, cbk: any) {
    cbk()()
  }

  f() {
    console.log(this.owner)
  }

The callback is passed from the component template

<button mat-raised-button (click)="sendDeleteRequest(deleteCredBtn, f)" color="warn" #deleteCredBtn="matButton">Delete</button>

However the f function will raise a ERROR TypeError: this is undefined.

How can I preserve the context?

What I tried

  1. Saving this in a self variable inside the f function to print self.owner
  2. Returning a lambda function from f
  3. Using bind(this) when invoking cbk from sendDeleteRequest

None of them have worked.

CodePudding user response:

Interesting. I did not know that the this context got dropped when passing in a function as an argument from the view template.

You can however pass in a reference to the component instance using this directly in the template, which would allow you to do something similar to the below:

  @Component({}) export class MyComp {
    testStr = "Value on componentContext";
    
    sendDeleteRequest(btn: MatButton, cbk: Function, componentContext: MyComp)
    {
      cbk.bind(componentContext)();
    }
    
    test() 
    {
      console.log(this.testStr);
    }

  }
<button mat-raised-button (click)="sendDeleteRequest(deleteCredBtn, test, this)" color="warn" #deleteCredBtn="matButton">Delete</button>

It feels a bit hacky, but it seems to work as expected.

  • Related