+ Start a Discussion
Aleksey SheldagaevAleksey Sheldagaev 

Get child component by aura:id using find() method

Can sombody explain why I get 'null' in my component's controller when trying to find child component by aura:id within aura:iteration
Here are markup and controller code example:
<aura:component>
  <aura:attribute name="someObjs" type="Object[]" />
  <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
  <div class="wrapper">
    <ui:button label="Click me" press="{!c.changeObjectTxt}" />

    <aura:iteration items="{!v.someObjs}" var="obj">
      <c:SimpleChildComponent someText="{!obj.txt}" aura:id="item_{!obj.id}" />
    </aura:iteration>
  </div>
</aura:component>
({
    doInit: function(cmp, event, helper) {
        var objs = [
                {id: 11, txt: 'First object'},
                {id: 12, txt: 'Second object'},
                {id: 13, txt: 'Third object'}
            ];
        
        cmp.set('v.someObjs', objs);
    },
    
    changeObjectTxt: function(cmp, event, helper) {
        var chCmp = cmp.find('item_12');
        
        console.log(chCmp);
    }
})


 
Best Answer chosen by Aleksey Sheldagaev
James LoghryJames Loghry
I don't think merge fields are supported in the aura:id attribute.  I could be wrong, but an easy test would be to replace item_{!obj.id} with item_12 and see how it works.

I would structure your component a bit differently though and do this via a Lightning event.  For instance, create an application event that you fire in your "changeObjectTxt" method, and then implement a handler in the simplechildcomponent that calls its own controller method.

All Answers

James LoghryJames Loghry
I don't think merge fields are supported in the aura:id attribute.  I could be wrong, but an easy test would be to replace item_{!obj.id} with item_12 and see how it works.

I would structure your component a bit differently though and do this via a Lightning event.  For instance, create an application event that you fire in your "changeObjectTxt" method, and then implement a handler in the simplechildcomponent that calls its own controller method.
This was selected as the best answer
Michał Zadrużyński 2Michał Zadrużyński 2
aura:id doesn't support expressions, you can try use html id.
<c:SimpleChildComponent someText="{!obj.txt}" id="item_{!obj.id}" />

and the get it in controller by:
$A.getComponent("item_12")



 
Zach Li 13Zach Li 13
Actutally component.find("your aura id") will return an array of the child components if you give them the same aura:id. You can then loop throught it and call the corresponding method.