Gaurav Gupta
Gaurav Gupta

Reputation: 185

Applying CSS class conditionally in Angular2

I have below HTML code which recursively create list items based on list returned from Component and I want to apply 'first-child' CSS class to first List item only.

<ul class="link-list-horz">
<li *ngFor="let menu of menulist" [ngClass]="first-child:">
 <a href="">{{menu}}</a>
</li>
</ul>

.first-child a 
{
    border-radius: 10; 
}

export class AppComponent  { 
   name = 'Quiz'; 
   menulist = ['Home','AngularQuiz'] ;  
   useremailid = 'Gaurav-Gupta'; 
}

Please suggest. I am totally new to Angular2.

Upvotes: 3

Views: 3052

Answers (1)

Yaron Schwimmer
Yaron Schwimmer

Reputation: 5357

ngClass needs a condition to know whether to set that class on the element. You can use the built-in index that comes with ngFor for that.

Try this:

<li *ngFor="let menu of menulist; let i=index" [ngClass]="{'first-child': i === 0}">

Upvotes: 2

Related Questions