Angular 2 add css class to selected item

Viewed 2155

How can I in Angular 2 add active class to selected item on click and remove that class on again click. But for multiple items in list.

<li *ngFor="let item of items" (click)="itemSelected(item)">
  <p>{{ item }}</p>
</li>

For example I have list of 5 items. Click on first item add class active and then for fifth item add also class active.

2 Answers

You can use the syntax from here:

<li *ngFor="let item of items" (click)="selectItem(item)" [class.selected]="isSelected(item)">
    <p>{{ item }}</p>
</li>

This seems a bit more idiomatic than using ng-class.

Related