Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

give active class onclick in ngFor angular 2

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?

like image 323
Vugar Ahmadov Avatar asked May 31 '17 14:05

Vugar Ahmadov


1 Answers

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;
   }
}
like image 138
doppelgunner Avatar answered Sep 21 '22 18:09

doppelgunner