0

When passing an argument, the context is lost to the function. How can I bind it in my typescript file?

import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular";

  getName(): string {
    return this.name;
  }

  onAction(cb: Function) {
    return cb();
  }
}

<p>
  {{onAction(getName)}}
</p>

Error: Cannot read property 'name' of undefined

If you make the binding in the template, then this will work.

<p>
  {{onAction(getName).bind(this)}}
</p>

But I would like to make the linking in the controller.

I would be grateful for any help!

Vladislav
  • 125
  • 6
  • *"If you make the binding in the template, then this will work."* I don't think it will, it has the `.bind(this)` in the wrong place. Shouldn't it be `{{onAction(getName.bind(this))}}`? – T.J. Crowder Apr 06 '21 at 07:41
  • Related: [How to access the correct `this` inside a callback?](https://stackoverflow.com/q/20279484/218196) – Felix Kling Apr 06 '21 at 07:45
  • What's the purpose of `onAction` here? Why are you not doing `{{getName()}}` directly? – Felix Kling Apr 06 '21 at 07:47
  • On a side note - don't use functions in the templates unless you use the `OnPush` change detection strategy. It's a HUGE performance hit (since basically every possible change runs change detection, since it can't know if the function needs to be re-evaluated or not) and, depending what you do in the inner function, can cause other issues in lifecycle hooks. – TotallyNewb Apr 06 '21 at 07:48

1 Answers1

0

If I understand you correctly, you can do the binding in the constructor in AppComponent:

export class AppComponent {
    name = "Angular";

    constructor() {                             // ***
        this.getName = this.getName.bind(this); // ***
    }                                           // ***
  
    getName(): string {
      return this.name;
    }
  
    onAction(cb: Function) {
      return cb();
    }
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875