give active class onclick in ngFor angular 2

邮差的信 提交于 2019-11-28 21:42:58
Eduardo Vargas

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;

doppelgunner

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

I believe you can find your answer here: AngularJs - Best-Practices on adding an active class on click (ng-repeat)

You can target and apply CSS to an item/object through Angular's $index. The post explains and demonstrates the logic better than I can.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!