加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:38:19 所属栏目:安全 来源:网络整理
导读:我建立了一个ul,只想在第一个li元素上设置该类. 我想把class =“active”设置在第一个li上.我将索引转换为类属性,但这不是我想要的. import { Component,View,NgFor,Inject,forwardRef,Input,NgIf,FORM_DIRECTIVES } from 'angular2/angular2';@Component({
我建立了一个ul,只想在第一个li元素上设置该类.

我想把class =“active”设置在第一个li上.我将索引转换为类属性,但这不是我想要的.

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,添加了第一个局部变量,因此原始解决方案可以重写为

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

见Angular 2 – ngFor – local variable “first” does not work

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读