2

I want to create a Lightning component where i can define some custom actions which can be used by the component which is creating instance. It will be very similar to the onrowselection, onsort actions on lightning:datatable or onclick of lightning:button.

Anybody knows whether it possible for custom components in lightning, if yes then how?

0
16

You can pass a reference to the parent into the child, so in the parent component:

<aura:method name="parentMethod" .../>

<c:child parent="{! this }" ... />

and in the child component you can then invoke the parent method:

<aura:attribute name="parent" type="Aura.Component" required="true"/>

someMethod: function(component, event, helper) {
    var p = component.get("v.parent");
    p.parentMethod();
}

This can sometimes be cleaner than using a component event that others have commented about. But best to learn about both techniques.

1
  • FYI, this approach for some reasons no longer work in Salesforce community, experience cloud.
    – Wayne Ni
    Jul 7 at 2:42
2

Unfortunately methods of a parent component cannot be called from a child component, it works the other way around.

I highly encourage you to read my blog post about Lightning Inter-Component Communication Patterns. This covers the different communication means that you can use.

0
1

Just add sth on top of the answer. Except pass the parent component into child component, you can also set up aura.action in your child component and link the invoke action to the parent method.

<!-- child.cmp -->
<aura:component>
    <aura:attribute name="onclick" type="Aura.Action"/>

    <p>Child component with Aura.Action attribute</p>
    <lightning:button label="Execute the passed action" onclick="{!v.onclick}"/>
</aura:component>

Parent component:

<!-- parent.cmp -->
<aura:component>
    <p>Parent component passes handler action to c:child</p>
     <c:child onclick="{!c.parentAction}"/>
</aura:component>

But of course, the method hook up will be a lot simpler in lwc.

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