Angular2仅在第一个元素上使用ng-for时如何设置元素类名称 [英] Angular2 how to set element class name when using ng-for, only on first element

查看:79
本文介绍了Angular2仅在第一个元素上使用ng-for时如何设置元素类名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个ul,并且只想在第一个li元素上设置该类.

I have building a ul and want to set the class only on the first li element.

我只想在第一个li上设置class="active".我确实将索引添加到class属性中,但这不是我想要的.

I want to set the class="active" only on the first li. I do get the index into the class attribute but that isn't what I want.

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要求

您只需使用此行即可实现

You can achieve by simply using this line

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

很高兴:)

更新

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

With beta 15 the first local variable was added, so the original solution can be rewritten as

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

请参见 Angular 2-ngFor-local变量"first"不起作用

这篇关于Angular2仅在第一个元素上使用ng-for时如何设置元素类名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆