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?

7
  • @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.
    – itsmebasti
    Nov 21, 2017 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, 2017 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. Nov 21, 2017 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, 2017 at 18:01

1 Answer 1

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:

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .