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
- Saving
this
in aself
variable inside thef
function to printself.owner
- Returning a lambda function from
f
- Using
bind(this)
when invokingcbk
fromsendDeleteRequest
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.