Access Items Size and Other attributes of Model inside ListView

nativescriptcore

#1

Hi
I want to access items size inside ListView. Also I want know how to access other attributes of Model inside a ListView. Following is Example:

<ListView items="{{ items }}" row="1" separatorColor="blue" itemTemplateSelector="$index">
    <ListView.itemTemplate>
        <StackLayout>
            <Label textWrap="true" textAlignment="center" marginTop="20dpi">
                <label.formattedText>
                    <formattedString>
                        <formattedString.spans>
                            <span text="Item "/>
                            <span text="{{ $index+1 }}"/>
                            <span text=" Of "/>
                            <span text="{{ items.length }}"/>
                        </formattedString.spans>
                    </formattedString>
                </label.formattedText>
            </Label>
        </StackLayout>
    </ListView.itemTemplate>
</ListView>

I face problem accesing items.length.

Thanks,
Rakesh


#2

Use $parent.items.length.

More info: https://docs.nativescript.org/core-concepts/data-binding#binding-to-a-parent-binding-context


#3

Thanks @manojdcoder for the link. I checked on playground https://play.nativescript.org/?template=play-tsc using $parent.items.length but no luck.


#4

In my case I used label without formatted text, when accessing multiple levels above, you have use $parents['ComponentName'].


#5

Thanks @manojdcoder. It works just fine.


#6

Though the screen is rendered correctly I get following error on console when I use $parents[‘ListView’].items.length:

JS: Binding: Property: ‘items’ is invalid or does not exist. SourceProperty: ‘$parents[‘ListView’].items.length’

I have items initialised to empty array in the constructor.


#7

If you want to eliminate the error log, then use

 <span text="{{ $parents['ListView'].items, $parents['ListView'].items.length }}" />

#8

This is better. Thanks @manojdcoder :slight_smile: