[SalesForce] Child Lightning Component needs parent init to work. Doable without dynamic components

When I load this Lightning component a child component's init gets a null pointer as an attribute doesn't yet exist. I is populated via an Apex action during the parent components init. I know that a Child components init is called before the parents init. Nonetheless I need to make this work without dynamic components. And I'd expect this to be a very common scenario.

Can this be solved by events or change handlers or refresh view calls??

Markup

<aura:component controller="MyCtrl" implements="force:lightningQuickAction,force:hasRecordId">
    <aura:attribute name="attributes" type="List" access="private" />

    <aura:handler name="init" value="{!this}" action="{!c.init}" />

    <c:attributeList items="{!v.attributes}" />
</aura:component>

Controller

({
    init: function(cmp, evt, helper) {
        var action = cmp.get("c.queryAttributes");
        action.setCallback(this, function(response) {
            cmp.set("v.attributes", response.getReturnValue());
        });

        $A.enqueueAction(action);   
    },
});

Best Answer

I tend to use both an init method and a change handler on the attribute that could be set after init e.g. of such a child component:

<aura:component access="global">

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

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:handler name="change" value="{!v.topicName}" action="{!c.doInit}"/>

</aura:component>

JS:

({
    doInit : function(component, event, helper) {
        var topicName = component.get('v.topicName');

        if(!$A.util.isEmpty(topicName)) {
            // Do whatever I need to do
        }
    }
})
Related Topic