give active class onclick in ngFor angular 2
just make an index property. use let i = index
to set the index using (click) event. Then check if selectedIndex === i
if yes the set class "active" to true
<ul class="sub_modules">
<li *ngFor="let subModule of subModules; let i = index"
[class.active]="selectedIndex === i"
(click)="setIndex(i)">
<a>{{ subModule.name }}</a>
</li>
</ul>
Then on typescript file: just set selectedIndex.
export class ClassName {
selectedIndex: number = null;
setIndex(index: number) {
selectedIndex = index;
}
}
You can do something like:
<ul class="sub_modules">
<li (click)="activateClass(subModule)"
*ngFor="let subModule of subModules"
[ngClass]="{'active': subModule.active}">
<a>{{ subModule.name }}</a>
</li>
</ul>
On The component
activateClass(subModule){
subModule.active = !subModule.active;
}
On the Ng class the first property is the class you wanna add and the second is the condition;