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.
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.
The code is looking something like this:
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?
I got a solution (and it's easy), when you receive the JSON data and save it in a variable of yours (in your case its called
menu
) add tomenu
a new field called classes and render it in the template!Example:
and in the template you can render it easliy
It seems like your variable isSelected is shared across the list. Change the variable to track the index instead.
render it with
Working http://plnkr.co/edit/7aDLNnhS8MQ1mJVfhGRR
Add
#clickState
to your row in the*ngFor
There are some redundant
'
. I guess you want to bind the value of the propertyisSelected
not the'isSelected'
string (same withfrst
)