2015-11-18 32 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> 
相关问题