Angular change Background of clicked ngFor li

人走茶凉 提交于 2020-03-05 04:09:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!