[SalesForce] component.get is giving null on parents component’s controller

I am trying to pass a string literal to parent component as attribute.

Child Component code:

 <div class="slds-form-element slds-hint-parent slds-has-divider--bottom">
   <h1>{!v.assessment.N2__c}</h1>
    <div class="slds-form-element__control">
      <c:PicklistSelect objectName="DEL_Assessment__c" fieldName="N2__c" value="{!v.assessment.N2__c}"/>
    </div>
  </div> 

Defining attribute on Parent component PicklistSelect :

<aura:attribute name="value" type="String"/> 

Rendering code on parent component :

<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<h1>'Passed literal value '+{!v.value}</h1>

Till here it is working well and on the layout of both parent and child the {!v.value} is printing.

But when i try to retriew the same in parent component PicklistSelect's controllers doInit function it is giving null

var value=component.get('v.value');
alert(value);

This alert is giving null, am i missing something while passing or initializing the attribute?

But when i pass a hard-coded value as below – in this case on parent controller the popup is giving the defined value

      <c:PicklistSelect objectName="DEL_Assessment__c" fieldName="N2__c" value="Hello"/>

Best Answer

First of all, using attribute name as value is not recommended. The reason for not getting the expected value in the alert is that the method named doInit is fired much before the value is passed to the component. For getting the value, you can use another handler as follows, Suppose your attribute name is myvalue,

<aura:handler name="change" value="{!v.myvalue}" action="{!c.methodName}"/>

So when the attribute value is changed, it can be captured in the method.