Angular 2 Generate Class Name Based on ngFor Index

I don't really understand your problem ;-)

There are two ways to set classes for a specific element:

  • The way you do with curly brackets:

    @Component({
      selector: 'my-app',
      template: `
        <div class="product-detail__variants">
          <template ngFor #variant [ngForOf]="variants" #index="index">
            <div *ngIf="currentVariant == index">
              <div class="product-detail-carousel-{{index}}">
                Test
              </div>
            </div>
          </template>
        </div>
      `,
      styles: [
        '.product-detail-carousel-2 { color: red }'
      ]
    })
    

    Test is displayed only for the third element (index 2) and in red.

  • As suggested by @Langley using the ngClass directive

    import {NgClass} from 'angular2/common';
    
    @Component({
      selector: 'my-app',
      template: `
        <div class="product-detail__variants">
          <template ngFor #variant [ngForOf]="variants" #index="index">
            <div *ngIf="currentVariant == index">
              <div class="product-detail-carousel-{{index}}">
                Test
              </div>
            </div>
          </template>
        </div>
      `,
      styles: [
        '.product-detail-carousel-2 { color: red }'
      ],
      directives: [ NgClass ]
    })
    

    The different is that you need to specify the NgClass directive within the providers attribute of your component. Again Test is displayed only for the third element (index 2) and in red.

Your following sentences: "The value variants is an empty array of a set length. variant thus has no value. currentVariant is a number that by default equals 0.". How do you expect something to be displayed if your array is empty. An ngFor is an iteration...

Hope it helps you, Thierry