Angular2 how to set element class name when using ng-for, only on first element

As of this post date the docs show:

first as isFirst

so:

<div *ngFor="let item of items; first as isFirst">
    ... etc

Hash syntax gives me Template parse errors (@angular 2.2.0), I had to use let instead.

<ul>
  <li *ngFor="let item of items; let i = index; let firstItem = first; let lastItem = last" [ngClass]="{ active: firstItem }">
    {{ i }} {{ firstItem }} {{ lastItem }} {{ item }} 
  </li>
</ul>

As requested by @jeff

You can achieve by simply using this line

<li *ngFor="let tab of tabs; let index = index" [class.active]="index == 0" ...>

Glad it helped :)

Update

With beta 15 the first local variable was added, so the original solution can be rewritten as

<li *ngFor="let tab of tabs; let isFirst = first" [class.active]="isFirst" ...>

See Angular 2 - ngFor - local variable “first” does not work

Tags:

Angular