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.

2 Answers 2

1

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
    Commented May 21, 2021 at 0:13
0

@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
    Commented May 20, 2021 at 2:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .