Add and Remove class in Angular

Bhaskararao Gummidi picture Bhaskararao Gummidi · Jan 3, 2018 · Viewed 22k times · Source

I want to add background color to the li element when clicked but when I clicked another li element the previous li element background color remains unchanged.

component.html

<div class="col-md-3 categories">
  <h3>News By Type</h3>
  <ul>
    <li class="cat" id="cat_{{i}}" *ngFor="let category of categories; let i = index" (click)="sortNewsItems($event,category,i)"><img src="../assets/images/news.jpg" width="70"><h4>{{category}}</h4></li>
  </ul>
</div>

component.ts

sortNewsItems(event,cat,index) {
  event.target.classList.add('cat_active');
}

Answer

Aravind picture Aravind · Jan 3, 2018

You should use srcElement of the $event

sortNewsItems(event,cat,index) {
  event.srcElement.classList.add('cat_active');
}

Read this answer and use its demo