单击 ngFor li 的角度变化背景 [英] Angular change Background of clicked ngFor li
问题描述
我有一个 ul 元素和一些 li 我用 *ngFor 得到那些 li.它们的背景颜色是白色,但如果我点击它们,我想将背景颜色更改为红色.但我只想更改我点击的 li 的背景颜色,而不是每个 li.
<h1>我的孩子们</h1><ul class="list-group"><li style="cursor: pointer" class="list-group-item" *ngFor="let Child of children" (click)="onChildSelect(Child)" >{{Child.Name}}
我会将此添加到您的 li:
[style.background-color]="Child.IsChildSelected"
制作:
<li style="cursor:pointer" class="list-group-item"*ngFor="让孩子的孩子"(点击)="onChildSelect(Child)"[style.background-color]="Child.BackgroundColour" >
然后您的点击函数应该更改子背景颜色(您可以将其作为字符串返回).例如:
onChildSelect(Child){//这会起作用,但如果您存储了先前选择的子项//最好把那个变成白色for(让myChild of this.children){myChild.BackgroundColour = "白色";}Child.BackgroundColour = "红色";}
如有必要,您可以使函数更复杂以具有多种颜色或将其他子项更改为未选择的颜色.
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>
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.
这篇关于单击 ngFor li 的角度变化背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!