Angular2 как установить имя класса элемента при использовании ng-for, только для первого элемента
Я создаю ul
и хочу установить класс только в первом элементе li
.
Я хочу установить 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;
}
Ответы
Ответ 1
Как запрошено @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 - локальная переменная "первая" не работает
Ответ 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>