codefreaK
codefreaK

Reputation: 3662

How to set default class to first element of *ngFor in angular

<ul class="nav flex-column">


  <ng-container *ngFor="let cat of Category"  >
    <span>{{change}}</span>
    <li class="nav-item">
        <a class="nav-link "  [class.bg]="temp===cat" (click)="clicked(cat)" href="#">{{cat}}</a>  
    </li>
  </ng-container>

</ul>

I have a sidebar and I want by default to show the first li anchor tag with active class and after that when I click other li I need to change . I have implemented the later part but how to set the default class

EDIT:-

   <li class="nav-item"  [class.bg]="change === true && i==0 ">
        <a class="nav-link "  [class.bg]="temp===cat" (click)="clicked(cat)" href="#">{{cat}}</a>  
    </li>

I used variable called change to check if the menu is not clicked and index variable i as suggested by Penggy to determine the first menu item and the code works

But I found out another thing and if somebody can help me understand it would be great

<a class="nav-link "  [class.bg]="temp===cat" [class.bg]="change === true && i==0 " (click)="clicked(cat)" href="#">{{cat}}</a> 

the above code works but it stops working if you change the order of [class.bg ] statements {{cat}} The above code does not work why is this

Upvotes: 2

Views: 2864

Answers (2)

Pengyy
Pengyy

Reputation: 38171

NgFor exports index variable which means for the index of the current element in array, see doc. You just need to declare it in ngFor expression in order to use it.

 <ng-container *ngFor="let cat of Category; let i = index;"  >
   <span>{{change}}</span>
   <li class="nav-item" [ngClass]="{'active-class': i === 0}">
     <a class="nav-link "  [class.bg]="temp===cat" (click)="clicked(cat)" href="#">{{cat}}</a>  
   </li>
 </ng-container>

You can also use first variable exported by ngFor.

 <ng-container *ngFor="let cat of Category; let f = first;"  >
   <span>{{change}}</span>
   <li class="nav-item" [ngClass]="{'active-class': f}">
     <a class="nav-link "  [class.bg]="temp===cat" (click)="clicked(cat)" href="#">{{cat}}</a>  
   </li>
 </ng-container>

Upvotes: 5

Pardeep Jain
Pardeep Jain

Reputation: 86740

Try this -

<li class="nav-item">
        <a class="nav-link "  [ngClass]='{"bg": temp===cat}' (click)="clicked(cat)" href="#">{{cat}}</a>  
    </li>

Upvotes: 0

Related Questions