Angular2如何在使用ng-for时仅在第一个元素上设置元素class名称

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

我正在构建一个 ul 并且只想在第一个 li 元素上设置 class。

我只想在第一行设置 class="active"。我确实将索引放入 class 属性,但这不是我想要的。

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;


}

根据@jeff 的要求

只需使用这一行就可以实现

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

很高兴它有所帮助:)

更新

在 beta 15 中添加了 first 局部变量,因此原始解决方案可以重写为

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

哈希语法给了我 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>

文档显示截至 post 日期:

first as isFirst

所以:

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