I have a parent component like
export default class Parent extends LightningElement {
onResult() {
this.doSomething();
}
}
<template>
<c-child result-callback={onResult}></c-child>
</template>
and a child component:
export default class Child extends LightningElement {
@api resultCallback;
onClick() {
this.resultCallback();
}
}
<template>
<button onclick={onClick}>click me</button>
</template>
The issue seems to be that when this.resultCallback()
runs, which calls the parent's onResult
method, this
is still the child component.
LWCs seem to magically autobind methods, so I'm not sure if this a LWC bug or if I'm missing something.
How does a parent element pass a callback to a child LWC?
Best Answer
you have to bind the method before passing it to the child.