Search code examples
angularng-classngfor

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?


Solution

  • 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;