How to check List size in aura:iteration

  • I am showing list of opportunity in a Lightning component. And I want to display them if the opportunity list size > 0 . i.e here ( opportunityList > 0)

    <lightning:select name="selectOpportunity" label="" required="false">
                <aura:iteration items="{!v.opportunityList}" var="opp">
                    <option value="{!opp.Id}" text="{!opp.Name}"></option>
                </aura:iteration>
    </lightning:select>
    
  • sfdcfox

    sfdcfox Correct answer

    3 years ago

    There's a handful of ways, but the most robust would probably be to see if it's not(empty(...)):

    <aura:if isTrue="{!not(empty(v.opportunityList))}"> ...
    

    This will suppress rendering if the list is empty, or null, or undefined...

    I was going to suggest `.length > 0` but this is much better

    Great !! it works

    @Sebastian Kessel , what is the other way?

    `{!v.opportunityList.length > 0}` but I would go with the suggested solution. It is much better, because it accounts for null/undefined.

    can we get the length of an object element inside lightning component alone?

    @cookie Objects don't have a length, but we can get the length of an Array (List) or String.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM