我構建了一個ul
並且只想在第一個li
元素上設置該類。Angular2如何在使用ng-for時設置元素類名稱,僅在第一個元素上使用
我想僅在第一個裏設置class="active"
。我確實將索引放入類屬性中,但這不是我想要的。
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;
}
'[class.active] =「index == 0」' –
@Eric - 完美。謝謝。 (使它成爲答案) – jeff
哦,好的,馬上:) –