give active class onclick in ngFor angular 2

Viewed 57118

Hi I have unordered list and all of them have active class. I want to toggle active class when clicked to any list item. My code is like this

<ul class="sub_modules">
  <li *ngFor="let subModule of subModules" class="active">
    <a>{{ subModule.name }}</a>
  </li>
</ul>

can anyone help me to do this?

5 Answers

I'd like to add & clarify a possible misconception:

  • You can only add classes via via [ngClass].
  • You can NOT add selectors like the :active selector.
<li [ngClass]="{'active': isActive === true}">

Mind the difference:

.li.active {
  // This works! :)
}

.li:active {
  // This doesn't work! :(
}

It might be obvious for some, but took me ~15 minutes of trial & error to understand.

the loop
<div *ngFor="let item of divs; let i = index">
    <app-cool [index]="i"></app-cool>
</div>

the <app-cool></app-cool> html  
<div (click)="setActive()"  [class.active]="isActive()">

</div> 

the <app-cool></app-cool> ts
static activeIndex = -1;

@Input() index: number = -1;
    
public setActive(): void{
    ThisClass.activeIndex = this.index;
}

public isActive(): boolean{
    return ThisClass.activeIndex === this.index;
}
Related