简体   繁体   English

如何在没有本地索引管理器的* ngFor Angular组件中使用[ngClass]?

[英]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. 似乎target.active的值从undefined变为true ,从false变为true等等, 样式未设置。 (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. NB,我知道如何通过从不同的角度接近它来解决它。 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. 我的问题的目的是学会以更加专横的方式实现所要求的行为。

target here: target

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

doesn't refer to menu , it refers to the event. 不是指menu ,而是指事件。 But based on your ngClass directive: 但是基于你的ngClass指令:

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

You need to set active to menu variable and so it can be done like this: 您需要将active设置为menu变量,因此可以这样做:

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

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] } }]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM