How to set background of selected/clicked ion-item in a ion-list

given a ionic2 app that renders a ion-list with ion-item elements in it, what’s the recommended way to highlight the selected element of the list, which is, the element the user last clicked?

my plan was to to use the (click) callback and maintain a selectedIndex in my component, and then do something like this:

<ion-item *ngFor="let track of list; let idx = index" (click)="onItemClicked(idx)" class="idx===currentSelected ? 'selected' : null"> ... </ion-item>

whereby the .selected is defined in the scss.
however it did not work (the click event handling works fine, but the color stays unchanged)

i also tried “ngClass” and played with “[color]”, but non worked.

interestingly, the hover-effect worked right away using this scss:

ion-item:hover { background-color: lightslategray !important; }

but the feature to prominently highlight the selected item (ie. the item which the user last clicked) is even more important but i could not achieve it yet.

==> any hints or pointers to relevant docu would be greatly appreciated! thanks!

[class.selected]="idx === currentSelected"

4 Likes

awesome - even more elegant than i had hoped :smile:

worked straight away

thanks…!!

Have the same situation whats your ts code for getting the currentselected and index?
Was to fast to ask the question got it to work, nice solution.

awesome! had to change the color of the text instead of the item’s background but this works like a charm!

what is currentSelected?
I can’t find it anywhere

i don’t understand , please give me a details
tnx

Can u give us a detail? I have the problem too

please give us in detail…thanks. i am also facing the same issue but i am not able to understand it

Declare currentSelected as a variable in your .ts file, then set it equal to the id you are passing through to the function on click:

export class somePage implements OnInit {
...
currentSelected: Number = null;
...

onItemClicked(idx) {
      this.currentSelected = idx;
}
1 Like

On html

<ion-item (click)=“function(index)” [ngClass]="{‘activated’: (active == index),‘deactivated’: (active != index)}" >

On ts
declare the variable active as global and inside your function write this
function(index){
this.active = index
}

hope it helps

thank you

2 Likes