0

I am new to lwc. I have a method in the child component which returns a string. I called the child method from the parent components but it fails to return the string to the parent component. Did I miss something?

child.js

@api
get myName(){
    console.log("child method myName");
    return "My name is Raj";
}

parent.html

<c-child></c-child>
<button onclick={callChildMethod}>Call Child Method</button>

parent.js

callChildMethod() {
    let childCmp = this.template.querySelector('c-child');
    let myName = childCmp.myName();
    console.log("Child name " + myName);
}

Thanks in advance.

0

to invoke a getter you don't need the parenthesis, if it was a public method, yes.

all you need is childCmp.myName

1
  • Thank you so much. – rjrajsaha May 21 at 0:13
-1

@rjrajsaha You need to follow the below steps for the child to parent communication in LWC: Firstly, define a custom event in the child web component. Add values that needs to be passed to the parent component. Dispatch the event.

const lwcEvt= new CustomEvent('eventname', {
   detail:{var1:value, var2: value} 
  });
 this.dispatchEvent(lwcEvt);

Here the eventName is the user-defined keyword for the event, which is going to be used in the child component tag in the parent component. Make sure that the event name should not start with the "on" word.

You need to then handle event on the parent lightning web component with the "oneventname" handler function. Here oneventname is the dispatched event in the child component(see above code), 'on' should be added before the event name.

<c-child-lwc-component oneventName={handleEvent}></c-child-lwc-component>

Finally, by using event.detail.variableName you will get the value which is passed from child lwc.

1
  • What the OP is doing is valid, he just confused a method with a getter property, just need to remove the parenthesis to get the value when invoking the property from parent to child – glls May 20 at 2:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.