1
votes

i've read through the Nativescript ListView documentation and searched Google and can't find any way to highlight the currently selected item of a Listview... Is this even possible? If so how can I go about it?

My code:

<ListView [items]="activeStockTakes" class="list-group" (itemTap)="selectActiveStockTake($event)">
                    <template let-activeStockTake="item">
                        <StackLayout>
                            <Label class="list-group-item" [text]="activeStockTake.UserCode + ' - ' + activeStockTake.Comment"></Label>
                        </StackLayout>
                    </template>
                </ListView>
2

2 Answers

6
votes

Sure you can!

Define a class "highlight" in CSS:

.highlight {
  background-color: #eee;
}

Then assign it based on a condition in the view:

<StackLayout [class.highlight]="selectedItem && activeStockTake.UserCode === selectedItem.UserCode">

That selectedItem property is defined in your Component and assigned/updated when an item is picked in the list.

4
votes

I had the same problem, which Eddy's answer helped me to solve.

2 css classes: Selected and Unselected.

Get the listview element index by adding let-i="index" to the template.

Set the default class with class="Unselected"

Use a data binding to conditionally change the class of the selected listview item [class.Selected]="i===selectedIndex"

Feed the index of the selected element to the component with (tap)="selectMenu(i)"

In your component, create the variable selectedIndex and set it equal to the index of the selected element.

Tapping an element will now change its CSS class. If you have one element selected and tap a different element from the list, the new element will become selected and the first selection will become unselected.

CSS

    <ListView [items]="submenu">
        <template let-item="item" let-i="index">
            <Label [class.Selected]="i===selectedIndex" [text]="item" class="Unselected" (tap)="selectMenu(i)"></Label>
        </template>
    </ListView>

TS

selectedIndex: number;

selectMenu(i) {
    this.selectedIndex=i;
}