2016-01-13 41 views
8

我遇到了基於Angular 2 ngFor循環索引創建動態類名的問題。我不得不使用以下語法,因爲Angular 2不喜歡相同元素上的ngFor和ngIf。Angular 2根據ngFor指數生成類名

使用此語法,如何創建一個動態類名,其索引值爲{{index}}。我知道這是不正確的A2代碼,但我把它放在我的代碼示例中,向您展示我希望顯示的值的位置。

<div class="product-detail__variants"> 
    <template ngFor #variant [ngForOf]="variants" #index="index"> 
     <div *ngIf="currentVariant == index"> 
      <div class="product-detail-carousel-{{index}}"> 

      </div> 
     </div> 
    </template> 
</div> 

值「variants」是一個設定長度的空數組。 「變體」因此沒有價值。

「currentVariant」 是一個數字,在默認情況下等於0。

EDIT:上述此代碼是否正確。我有另一個無關的錯誤,我認爲這是連接到這個代碼。

+1

你試過用'ngClass'? https://angular.io/docs/ts/latest/api/common/NgClass-directive.html – Langley

+0

我的代碼顯然是有效的,另外一個額外的錯誤就是拋棄它。這段代碼是正確的! – AJStacy

回答

8

我真的不明白你的問題;-)

有兩種方法來設置類特定元素:

  • 你用兩個大括號做的方法:

    @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僅針對第三個元素(索引2)顯示並顯示爲紅色。

  • 由於使用ngClass指令

    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 ] 
    }) 
    

    不同的建議通過@Langley是,你需要你的組件的providers屬性中指定NgClass指令。 Test僅針對第三個元素(索引2)顯示,並以紅色顯示。

你的下面的句子:「的值variants是一組長度的空數組variant因而沒有值currentVariant是一個數字,在默認情況下等於0。」。如果你的數組是空的,你希望如何顯示。一個ngFor是一個迭代...

希望它可以幫助你, 蒂埃裏

+0

我沒有試圖顯示一個值,我只是試圖循環一個基於數值「numVariants」的次數,該值被轉換爲數組長度,以便ngFor循環(因爲ng-repeat不再存在)。 顯然我有另一個無關的錯誤,影響我的代碼,我的Angular 2代碼已經是正確的。感謝您爲我驗證。 – AJStacy