1

I'm rendering components in the body of another component:

<c:test>
    <input type="text" aura:id="fooBar" />
</c:test>

In this c:test component I'm trying to access the inner element by it's aura id, but I can't find it:

c:test

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

    <button onclick="{!c.find}">find</button>
    {!v.body}
</aura:component>

Controller:

find: function(cmp, event, helper) {
    console.log(cmp.find("fooBar"));
}

Result: (on init, or when I click the button)

undefined

Is there a way to access Components inside the own body?

  • @SebastianKessel thanks, I checked it, and it's not. It does also happen, when I do it on a button click, I will update my answer. – Basti Nov 21 '17 at 17:06
  • not sure i understand, but, !v.body seems to be empty, unless you are dynamically creating a component with an aura:id fooBar, i am not surprised cmp.find foobar is undefined. what makes you think that adding an HTML tag in within your component tag(s) will be added to the body (is there any documentation on this out of curiosity?) – glls Nov 21 '17 at 17:15
  • 1
    @glls the code works fine. {!v.body} in that case does exactly what you'd expect. renders whatever was entered between the beginning and end of the tag. – Sebastian Kessel Nov 21 '17 at 17:33
  • 1
    thanks! just wanted to know where it is stated that this should work =P. hopefully we can find a way to make this work (will check later today). – glls Nov 21 '17 at 18:01
1

There are a couple of problems with this approach.

  1. You haven't added the component - you would need to do this dynamically.
  2. Component encapsulation means that your find will not work if called from the parent component.

To solve this issue, first add the component dynamically:

doInit : function(cmp) {
    $A.createComponent(
        "c:test",
        {"aura:id": "testCmp"},
        function(testCmp, status, errorMessage){
            var body = cmp.get("v.body");
            body.push(newButton);
            cmp.set("v.body", body);
        }
    );
}

Then, to perform the find, you will need to define a method on the child component that performs the find and executes your action for you.

Eg:

cmp.find("testCmp").sampleMethod(arg1, … argN);

To define a method, look here:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.