Angular 更改点击 ngFor li 的背景

Angular change Background of clicked ngFor li

我有一个带有一些 li 的 ul 元素,我正在使用 *ngFor 获取这些 li。 它们的背景颜色是白色,但如果我单击它们,我想将背景颜色更改为红色。但我只想改变我点击的里的背景颜色,而不是每一个里。

<div class="Container">
  <h1>My Children</h1>
  <ul class="list-group">
    <li style="cursor: pointer" class="list-group-item" *ngFor="let Child of children" (click)="onChildSelect(Child)" >{{Child.Name}}
    </li>
  </ul>
</div>

我会把这个加到你的里:

[style.background-color]="Child.IsChildSelected"

成功:

<li style="cursor: pointer" class="list-group-item" 
    *ngFor="let Child of children" (click)="onChildSelect(Child)" 
    [style.background-color]="Child.BackgroundColour" >

然后您的点击函数应该更改子背景颜色(您可以 return 它作为一个字符串)。例如:

onChildSelect(Child)
{
    // This would work but if you have the previously selected child stored 
    // it would be better to just turn that one white
    for (let myChild of this.children) {
        myChild.BackgroundColour = "white";
    }

    Child.BackgroundColour = "red";
}

您可以使函数更复杂以具有多种颜色,或在必要时将其他子项更改为未选择的颜色。