4

I have a parent component name "ParentComp" which has 3 attributes A,B and C of type String. I have a nested component "ChildComponent". I want to change the value of parent component's attribute B from child's java script controller.

How can i do that?

  • 2
    you have to use events to communicate between the components. – Vamsi Krishna Oct 27 '15 at 4:56
  • i tried $A.getRoot but it return undefined . Communication via events is the last option. Does framework provides anything to let component know inside what component its running – Pranay Jaiswal Oct 27 '15 at 4:59
13

The framework will never have a way for you to get the parent component. That breaks encapsulation.

You have two options:

  1. Fire an event that your containing component can listen for and act upon.

  2. Pass in a reference to the attribute to the child component.

    <c:childComponent myValue="{!v.B}"/>
    

When the childComponent updates myValue, v.B will also update.

  • 1
    Second answer will suit my use case more.. Will try nd let u know. – Pranay Jaiswal Oct 30 '15 at 11:20
6

Hope this will help you out in your requirements.

  1. Create the event.

Event: setAttributeEvent

<aura:event type="COMPONENT">
    <aura:attribute name="attributeValue" type="String"/>
</aura:event>
  1. Register the event in child component.

Component: ChildComponent

<aura:component>
    <aura:registerEvent name="setAttribute" type="c:setAttributeEvent"/>
    <ui:inputText aura:id="val"/>
    <ui:button label="setParentAttributeValue" action="{!c.setValue}"/>
</aura:component>
  1. Fire the event through the child component controller.

Controller: ChildComponentController

({
    setValue: function(component, event, helper)
    {
        var inputfieldValue = component.find("val").get("v.value");
        var setEvent = component.getEvent("setAttribute");
        setEvent.setParams({"attributeValue":inputfieldValue});
        setEvent.fire();
    }
})
  1. Handle the event in parent component fired from child component.

Component: ParentComp

<aura:component>
    <aura:handler name="setAttribute" event="c:setAttributeEvent" action="{!c.setAttributeValue}"/> 
    <aura:attribute name="B" type="String"/>
    <c:ChildComponent/>
</aura:component>
  1. Perform the necessary action.

Controller: ParentCompController

({
    setAttributeValue: function(component, event, helper)
    {
        var eventValue= event.getParam("attributeValue");
        component.set("v.B", eventValue);
    }
})

PS: Name used in RegisterEvent should match with Handler name, else event will not be handled.

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.