2

I've two components:

<c:Lightning_component_Aura>
  <c:lwcLightningWebComponent aura:id="myLwcComponent" />
</c:Lightning_component_Aura>

I've declared a function inside LWC using @api. Now the documentation says, this method can be called from Parent component but the way they provided is for if parent component is also LWC component.

I would like to call this child LWC component from a parent Aura component. Like we do by provideding a aura:id to an Aura component and find that instance and call the aura method.

Aura Example:

component.find('childComponent').method1();

I tried supplying LWC an aura:id and call the @api method like this but it did not work.

Any suggestions on how to do that?

  • I haven't tried it myself but as far as I can say, you cannot do it this way here. If you need to call a JS from LWC, it has to be an ES6 module. – Jayant Das Jun 13 at 16:58
  • hmm .. do you know if there is then any way I can bind an attribute change handler such that, I change an attribute value in parent Aura cmp, and as a result it automatically change/call a method in child LWC cmp? – VarunC Jun 13 at 17:09
  • 2
    The answer in this question seems to have to done what you are asking for salesforce.stackexchange.com/questions/257371/… – RedDevil Jun 13 at 17:10
  • Thanks, that's exactly what I needed! – VarunC Jun 13 at 21:01
3

The public API of LWC components are exposed on the DOM element. The reason why your example doesn't work is because component.find() returns an Aura component instance, which in this case is the abstraction layer used to make LWC compatible with Aura. To access the underlying DOM element of an LWC component, you have to dig it out of the Aura component via the getElement method:

var auraCmp = component.find('childComponent');
var lwcElm = auraCmp.getElement();
lwcElm.method1();

Edit: Invoking the LWC method directly from the Aura component is supported. Both methods will work, but I recommend doing it the Aura way when developing in Aura.

  • 1
    Actually component.find('childComponent').method1(); did work. It was possibly some mistake in my code that it didn't work first time I tried. – VarunC Jun 14 at 7:15

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.