3

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.

1
  • 2
    Take a look at NgClass. Maybe this helps. Commented Oct 1, 2017 at 19:10

2 Answers 2

1

You can use:

[NgStyle] https://angular.io/api/common/NgStyle

[NgClass] https://angular.io/api/common/NgClass

For example:

<li *ngFor="let item of items" (click)="itemSelected(item)">
  <p [NgClass]="listSelectedItems.indexOf(item)>-1"?"your-active-class":"your-inactive-class" >{{ item }}</p>
</li>

With itemSelected() which add or remove item from listSelectedItems

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Can you please elaborate this answer with the corresponding code in the ts file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.