Angular 2 - Select clicked list item (Add 'active' class and remove from siblings)
You can use ngClass for what you are looking for:
<ul id="grouplist" class="list-group">
<li class="list-group-item" [ngClass]="{'active': selectedItem == item}" (click)="listClick($event, item)" *ngFor="let item of groups">
{{ item.name }}
</li>
</ul>
And in your listClick
just set the selected item to that item:
listClick(event, newValue) {
console.log(newValue);
this.selectedItem = newValue; // don't forget to update the model here
// ... do other stuff here ...
}
You can also just pass the index of the li
element to your component during a click event:
<ul id="grouplist" class="list-group">
<li *ngFor="let item of items; let i=index" (click)="select(i)"
[ngClass]="{'active': selectedIndex == i, 'list-group-item': true}" >
{{ item.text }}
</li>
</ul>
Then let you component set its selectedIndex
property:
@Component({
...
})
export class ItemListComponent {
...
selectedIndex: number;
select(index: number) {
this.selectedIndex = index;
}
}
The selectedIndex
is used by the template to determine whether to assign the active
class to the li
element.
See it in this Plunker