1

I have issue with accessing child component method in parent component

If there is single child component inside aura:iteration , if we use component.find("id").length in parent lightning component returns undefined for child component and the child component method is never called. If the number of child components is greater that one, component.find("id").length returns the correct number of child lightning components.

Is there any way to solve this issue.

1
  • 2
    Very difficult to tell what are you referring to when you say component. It could be a lightning base component like lightning:card, or a custom component, or even a simple HTML component. To avoid the audience playing a guessing game, please put your code here to help us understand your problem better.
    – Mahmood
    Commented Jan 1, 2018 at 11:47

2 Answers 2

8

I think your question is about the way find works where it only returns an array when more than one item is found. One way to address this is to add a helper method that always returns an array (of length zero, one or more):

asArray: function(component) {
    if (Array.isArray(component)) return component;
    else return component ? [component] : [];
},

so that code like this always works:

var children = helper.asArray(component.find("id"));
console.log(children.length);
1

I had this exact same problem and was able to find a fix. Lightning developer guide states the following about component.find() method:

If the local ID is unique, find() returns the component. If there are multiple components with the same local ID, find() returns an array of the components. If there is no matching local ID, find() returns undefined.

Note that it returns an array only when they are multiple components, but return a component (not an array) when there is only one component. Now, .length is not a property or method defined on the component (when you do component.find("id").length). Hence, it returns undefined.

Fix to this problem is to call the child method directly as follows: component.find("id").childmethodname()

Although, the answer is a little late, hope this will help someone.

You must log in to answer this question.

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