Lightning: aura:iteration - how to refer indexVar variable inside loop to access elements in List?

  • What is the way to refer index variable inside looping aura:iteration?

    The code below results in error:

    Failed to save undefined: expecting a positive integer, found 'indx' at column 10 of expression: v.labels[indx]: Source

        <aura:iteration var="item" items="{!v.items}" indexVar="indx">
                <label class="card-detail-label">{!v.labels[indx]}</label>
                <span class="card-detail-value">{!item}</span>  
  • It does not look like a variable defined as indexVar was meant to be used as part of another expression.

    e.g. this works

    <aura:iteration items="{!v.contacts}" var="item" indexVar="index">
    {!index} : {!item.FirstName}<br/>

    I think in your example "item" should be changed from final value to an object which has properties .label and .value, something like this:

    <aura:iteration var="item" items="{!v.items}">
                <label class="card-detail-label">{!item.label}</label>
                <span class="card-detail-value">{!item.value}</span>  

    Is there a way to add counter as integer as in `indexVar` gives string in return, which we cannot use to compare.

  • You can only address the "[]" notation using an integer. It throws an error because it is not possible to access an object in an array using a variable

    see this related question

    One alternative is to create a wrapper component that has all its properties already set as attributes and then iterate on it. The framework has a poor dynamic logic implementation.

    see @gaiser answer!

License under CC-BY-SA with attribution

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