css - How to use [ngClass] in a *ngFor Angular component without a local index keeper? -


i'm using following markup mark clicked component active.

<div *ngfor="let menu of menus;"      (click)="onclick($event,menu.link)"      [ngclass]="{'active':menu.active}">   {{menu.title}} </div> 

the method handling click follows.

onclick(target, link) {   target.active = !target.active;   this.router.navigate([{ outlets: { primary: [""], menus: [link] } }]); } 

it seems value of target.active goes undefined true false true etc. but style doesn't set. (i'm printing out whole component console , can't see addition of class' name.)

question: missing in approach?

nb, know how resolve approaching different angle. set local variable keeping index , setting like shown here. aim of question learn achieve requested behavior in more like-a-bossy way.

target here:

onclick(target, link) {   target.active = !target.active;   <------------   this.router.navigate([{ outlets: { primary: [""], menus: [link] } }]); } 

doesn't refer menu, refers event. based on ngclass directive:

[ngclass]="{'active':menu.active}"> 

you need set active menu variable , can done this:

<div *ngfor="let menu of menus;"      (click)="onclick(menu,menu.link)"      [ngclass]="{'active':menu.active}">   {{menu.title}} </div> 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -