2015-11-18 31 views
22

我構建了一個ul並且只想在第一個li元素上設置該類。Angular2如何在使用ng-for時設置元素類名稱,僅在第一個元素上使用

我想僅在第一個裏設置class="active"。我確實將索引放入類屬性中,但這不是我想要的。

import { Component, View, NgFor,Inject,forwardRef,Input, NgIf, FORM_DIRECTIVES } from 'angular2/angular2'; 
 
@Component({ 
 
    selector: 'tabs' 
 
}) 
 
@View({ 
 
    template: ` 
 
     <ul> 
 
      <li *ng-for="#tab of tabs;#index = index" class="{{index}}" (click)="selectTab(tab)">{{tab.tabTitle}}</li> 
 
     </ul> 
 
     <ng-content></ng-content> 
 
    `, 
 
    directives: [NgFor] 
 
}) 
 

 
export class Tabs { 
 
    get tabs() { 
 
     return this._tabs; 
 
    } 
 

 
    set tabs(value) { 
 
     this._tabs = value; 
 
    } 
 
    private _tabs; 
 

 
    constructor() { 
 
     console.log("ctor.Tabs"); 
 
     this._tabs = []; 
 
    } 
 

 
    selectTab(tab) { 
 
     this._tabs.forEach((tab) => { 
 
      tab.active = false; 
 
     }); 
 
     tab.active = true; 
 
    } 
 

 
    addTab(tab: Tab) { 
 
     if (this._tabs.length === 0) { 
 
      tab.active = true; 
 

 
     } 
 
     else { 
 
      tab.active = false; 
 
     } 
 
     this._tabs.push(tab); 
 
    } 
 
} 
 

 
@Component({ 
 
    selector: 'tab', 
 
    properties: ['tabTitle: tab-title'] 
 
}) 
 
@View({ 
 
    template: ` 
 
    <div [hidden]="!active" [class]="active"> 
 
     <ng-content/> 
 
    </div> 
 
    ` 
 
}) 
 
export class Tab { 
 
    @Input() index: number; 
 

 
    constructor(@Inject(forwardRef(() => Tabs)) tabs: Tabs) { 
 
     console.log("ctor.Tab") ; 
 
     tabs.addTab(this); 
 
     console.log(tabs); 
 
    } 
 

 
    get active() { 
 
     return this._active; 
 
    } 
 
    set active(value) { 
 
     this._active = value; 
 
    } 
 
    private _active; 
 

 

 
}

+0

'[class.active] =「index == 0」' –

+0

@Eric - 完美。謝謝。 (使它成爲答案) – jeff

+0

哦,好的,馬上:) –

回答

29

按照要求通過@jeff

您可以通過簡單地使用該行實現

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

高興它幫助:)

更新

隨着測試15 first局部變量中的溶液,所以原來的溶液可以被改寫爲

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

參見Angular 2 - ngFor - local variable 「first」 does not work

+1

如果我想添加'is-active',如何實現? '[class ['is-active']] = isFirst'不起作用。 – Hitmands

+1

@Hitmands'''[ngClass] =「{'is-active':isFirst}」''' – Guntram

+0

我真的不相信這會奏效。 BUUUT它確實...所以我想我需要更好地研究角度語法......感謝優雅的解決方案:) – MartinJH

2

哈希語法給我Template parse errors(@angular 2.2.0) ,我不得不使用let

<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> 
相關問題