Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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

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;      }
like image 668
jeff Avatar asked Nov 18 '15 02:11

jeff


2 Answers

As requested by @jeff

You can achieve by simply using this line

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

Glad it helped :)

Update

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" ...> 

See Angular 2 - ngFor - local variable “first” does not work

like image 185
Eric Martinez Avatar answered Sep 23 '22 13:09

Eric Martinez


Hash syntax gives me Template parse errors (@angular 2.2.0), I had to use let instead.

<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> 
like image 39
coni2k Avatar answered Sep 23 '22 13:09

coni2k