问题
I have an ul element with some li's Im getting those li's with *ngFor. Their background color is white but I want to change the background color to red if I click on them. But I only want to change the background color of the li I clicked on and not every 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>
回答1:
I would add this to your li:
[style.background-color]="Child.IsChildSelected"
Making it:
<li style="cursor: pointer" class="list-group-item"
*ngFor="let Child of children" (click)="onChildSelect(Child)"
[style.background-color]="Child.BackgroundColour" >
Then your click function should change the child background colour (you can return it as a string). eg:
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";
}
You can make the function more complex to have multiple colours or change the other children to a non selected colour if necessary.
来源:https://stackoverflow.com/questions/48277230/angular-change-background-of-clicked-ngfor-li