user5680735 user5680735 - 9 months ago 749
AngularJS Question

Angular2 - Add class to item on click

I have a bunch of list items and would like to highlight each one once it's clicked. This is easy for me to do in jQuery or even JavaScript but I'm lost when it comes to Angular2.

<li []="false" (click)="highlightItem($event)" [class.highlight]="isHighlighted($event)" *ngFor="#item of items"> {{item}} </li>

My component

export class HelloWorld {
items = ["pineapples", "apples", "tomatoes", "bread"];

highlightItem(event) {"data-selected", "true");

isHighlighted(event) {
return"data-selected") == "true";

Not sure where my mistake is or if I'm using a wrong method

Thanks in advance


You need to make an array in your class to store highlight status of an item:

hightlightStatus: Array<boolean> = [];

Declare local variable in the template associated with ngFor:

   <li []="false" 
       *ngFor="let item of items, let i = index">