give active class onclick in ngFor angular 2

后端 未结 3 977
灰色年华
灰色年华 2020-12-28 18:02

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

相关标签:
3条回答
  • 2020-12-28 18:31

    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.

    0 讨论(0)
  • 2020-12-28 18:45

    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;
       }
    }
    
    0 讨论(0)
  • 2020-12-28 18:46

    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;

    0 讨论(0)
提交回复
热议问题