我有一个正在使用 Angular 2 (RC1) 开发的应用程序。需要从数据库创建菜单。数据通过 Web Api 以 JSON 形式传送。我想递归地从数据构建菜单,以确保菜单的深度不是问题。
问题是当我想在 ngFor 循环的特定行上添加类时,类被添加到所有行而不是我想要的行。
代码看起来像这样:
sidenav.component.ts
import { Component, Input } from '@angular/core';
import { IMenu } from '../../../shared/models/menu.interface';
import { MenuComponent } from './menu.component';
@Component({
moduleId: module.id,
selector: 'sidenav',
templateUrl: 'sidenav.component.html',
directives: [MenuComponent]
})
export class SidenavComponent {
@Input() menu: IMeni[]
}
sidenav.component.html
...
<menu-view [menu]="menu"></menu-view>
...
menu.component.ts
import { Component, Input } from '@angular/core';
import { IMenu } from '../../../shared/models/menu.interface';
@Component({
moduleId: module.id,
selector: 'menu-view',
templateUrl: 'menu.component.html',
directives: [MenuComponent]
})
export class MenuComponent {
isSelected: boolean = false;
@Input() meni: IMeni[];
onSelect(): void {
this.isSelected = !this.isSelected;
}
}
menu.component.html
<ul>
<li *ngFor="let item of menu; let frst=first"
class="menu-list"
[ngClass]="{'active': 'isSelected', 'active': 'frst'}">
<a [routerLink]="[item.uri]" (click)="onSelect()" > {{item.name}}</a>
<meni-view [menu]="item.children"></meni-view>
</li>
</ul>
所以,当我点击 parent 时,所有 parent 都会变得活跃,而不仅仅是那个特定的 parent ,这将是令人满意的行为。我做错了什么?
最佳答案
您的变量 isSelected 似乎在整个列表中共享。改为更改变量以跟踪索引。
export class App {
menu = [{name: "Item 1", url: "/item1"}, {name: "Item 2", url: "/item2"},{name: "Item 3", url: "/item3"}];
selectedIdx = 0;
selectItem(index):void {
this.selectedIdx = index;
}
}
渲染它
<li *ngFor="let item of menu;let i = index"
class="menu-list" [ngClass]="{'active': selectedIdx == i}">
<a (click)="selectItem(i)"> {{item.name}}</a>
</li>
关于angular - ngFor 循环中的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37545947/