5

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?

0

2 Answers 2

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.

0
7

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.

0

You must log in to answer this question.

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