ngFor循环中的样式 [英] Style in ngFor loop

查看:255
本文介绍了ngFor循环中的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在Angular 2(RC1)中开发的应用程序.需要从数据库中创建菜单.数据通过Web Api以JSON形式传递.我想递归地从数据构建菜单,以确保菜单的深度不是问题.

I have an app which I'm developing in Angular 2 (RC1). The menu is need to be created from the database. Data is delivered via Web Api in JSON form. I would like to build menu from the data recursively, to be sure that depth of the menu is not an issue.

问题是当我想在ngFor循环的特定行上添加类,并且该类被添加到所有行而不是仅添加到我想添加的那一行时.

The problem is when I'm want to add class on particular row of ngFor loop, and the class is added to all rows instead of just one I want to.

代码看起来像这样:

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>

因此,当我单击父母"时,所有父母都会活跃,不仅是那个特定的父母,还会有令人满意的行为.我做错了什么?

So, when I click on parent all parents become active, not only that particular one, what will be satisfying behaviour. What I do wrong?

推荐答案

似乎您的变量 isSelected 在整个列表中共享.更改变量以跟踪索引.

It seems like your variable isSelected is shared across the list. Change the variable to track the index instead.

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

这篇关于ngFor循环中的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆