[SalesForce] Aura:Id of dynamically created compontns cannot be accessed

Below is my code to create the component dynamically – The component is "ui:inputselect"

$A.createComponent(
            RecoveryLineItem.Attributes[i].name,{
                "class" : "slds-input ",
                "aura:id" : 'ExampleId',
                "label" : RecoveryLineItem.Attributes[i].label,
                "multiple" : RecoveryLineItem.Attributes[i].multiple
            }, ....

..

console.log(component.find('ExampleId').get("v.value")) 

Or console.log(component.find('ExampleId'))
is Giving as 'Undefined"

How to access the aura:id of the dynamically created components?

Best Answer

Sorry can't comment yet.

But i have the same problem when using cmp.find() to get a dynamically created component the return value is always undefined.

I even tried it with the code provided in the documentation(https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/js_cb_dynamic_cmp_async.htm).

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

    <p aura:id="test">Dynamically created button</p>
    {!v.body}
</aura:component>


/*createComponentController.js*/
({
    doInit : function(cmp) {
        $A.createComponent(
            "ui:button",
            {
                "aura:id": "findableAuraId",
                "label": "Press Me",
                "press": cmp.getReference("c.handlePress")
            },
            function(newButton, status, errorMessage){
                //Add the new button to the body array
                if (status === "SUCCESS") {
                    var body = cmp.get("v.body");
                    body.push(newButton);
                    cmp.set("v.body", body);
                }
                else if (status === "INCOMPLETE") {
                    console.log("No response from server or client is offline.")
                    // Show offline error
                }
                else if (status === "ERROR") {
                    console.log("Error: " + errorMessage);
                    // Show error message
                }
            }
        );
    },

    handlePress : function(cmp) {
        console.log("button pressed");
        console.log(cmp.find("findableAuraId"));
    }
})

The first console log works, the second one returns 'undefined'

A possible workaround : cmp.find({ instancesOf : "auradocs:sampleComponent" }) which returns an array of all "auradocs:sampleComponent"

handlePress : function(cmp) {
    var button = cmp.find({ instancesOf : "ui:button" })[0];
    button.set("v.label", "test");
}