如何更改ngFor循环的div的文本颜色?

How to change the text color of div which is looped by ngFor?

我有一个使用 ngFor 循环的 div,现在每当我单击循环中的一个 div 时,我想更改该特定 div 的文本颜色,然后如果我在循环中单击任何其他 div,那么 div 只会更改他的颜色,而前一个单击的 div 会将其文本颜色更改为初始颜色价值。 [仅使用 Angular 2]。

例如:

<div *ngFor="let x of y; let i= index" (click)="changeColor()"></div>

您的问题的有效解决方案如下:

将模板代码更改为以下内容:

<div [ngClass]="{'selected-color' : i==selectedIndex}"
     *ngFor="let x of y; let i= index" (click)="changeColor(i)">

     <!-- print anything here -->

</div>

注意这里我添加了[ngClass]并绑定了一个条件。还要注意索引被传递到 changeColor(i)

现在在你的组件中 class:

public selectedIndex;

changeColor(i){
    this.selectedIndex = i;
  }

定义背景颜色css class,如你所愿:

.selected-color{
  background-color: red;
}

现在一切正常。