Gaurav Gupta Gaurav Gupta - 1 month ago 11
CSS Question

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>

.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.


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