user1675891
user1675891

Reputation:

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

I'm using the following markup to mark the clicked component as active.

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

The method handling the click is as follows.

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

It seems that the value of target.active goes from undefined to true to false to true etc. but the style doesn't get set. (I'm printing out the whole component to the console and can't see the addition of the class' name.)

Question: What am I missing in this approach?

NB, I know how to resolve it by approaching it from a different angle. I set up a local variable keeping the index and setting it like shown here. The aim of my question is to learn to achieve the requested behavior in a more like-a-bossy way.

Upvotes: 3

Views: 2145

Answers (2)

Andrei Matracaru
Andrei Matracaru

Reputation: 3671

Instead of passing in the $event, send it the actual menu object. Like this:

<div *ngFor="let menu of menus;"
     (click)="onClick(menu)"
     [ngClass]="{'active':menu.active}">
  {{menu.title}}
</div>

And in the component:

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

Upvotes: 0

Max Koretskyi
Max Koretskyi

Reputation: 105547

target here:

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

doesn't refer to menu, it refers to the event. But based on your ngClass directive:

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

You need to set active to menu variable and so it can be done like this:

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

Upvotes: 1

Related Questions