Search code examples
angularngfor

how to add class to particular `li` tag in ngFor loop?


Im trying to add class on mouseover in li tag on ngFor loop. but when mouseover the li tag all the li tag btn-success class is added. how to add class to particular li tag in ngFor loop?.

<li class="hhwtmainmenu" *ngFor="let headermenu of headermenus.header; let i=index; " [class.btn-success]="mouseOvered" (mouseout)="mouseOvered=false" (mouseover)="mouseOvered=true">
    {{headermenu.title}}
</li>

Solution

  • Not an excellent solution but will do the trick for you.

    <ul><li class="hhwtmainmenu"
      *ngFor="let headermenu of headermenus.header; let i=index; "
      [class.btn-success]="selectedIndex === i"
      (mouseout)="removeIndex(i)"
      (mouseover)="setIndex(i)">
    {{headermenu.title}}
    </li>
    </ul>
    

    For the methods in you component file:

      setIndex(index: number) {
    this.selectedIndex = index;
    }
    removeIndex(index: number) {
    this.selectedIndex = null;
    }