angular - ngFor 循环中的样式

标签 angular

我有一个正在使用 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>

工作 http://plnkr.co/edit/7aDLNnhS8MQ1mJVfhGRR

关于angular - ngFor 循环中的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37545947/

相关文章:

javascript - Angular react 形式 : Producing an array of checkbox values?

typescript - Angular2 将@Inputs 与<router-outlet> 一起使用

Angular 9 通用部署问题

angular - AngularDart无法在 'setAttribute'上执行 'Element': ')'不是有效的属性名称

node.js - 如何使用 Angular 4 设置 Nodemailer?

angular - 将AWS放大到Angular应用程序时出现错误: global is not defined

angular - 如何增加 mat-menu-item 的宽度?

javascript - ngrx/store 与 ngModel 引起了一些问题

javascript - 被 Rxjs Observable 构造函数和 'this' 参数混淆

javascript - Websocket-sockjs-InvalidStateError : The connection has not been established yet