Search code examples
angularngforng-style

Angular 2 - change list item bg-color individually using ngFor


How can I change the background color of a list item generated using ngFor? I want to change the background color of each list item individually when I click on one or hover it?

This is what I have now but it changes all of the line together when I click one line.

<ul class="list-group col-lg-6">
    <li href="#" class="list-group-item" [style.background-color]="whenClicked ? 'yellow' : 'none'" *ngFor="let recipe of Items "
     (click)="ChangeColor()">
      {{recipe.Title}}</li>

  </ul>

I've changed the code a bit according to suggestion of a member here. here it is now:

<ul class="list-group col-lg-6">
    <li href="#" class="list-group-item special-hover" *ngFor="let recipe of Items ">
      {{recipe.Title}}</li>

  </ul>

this is the css component:

.special-hover > li:active{
 background:#67EC32 
}

and this is the ts component:

import { Component } from '@angular/core';


@Component({
  selector: 'recipeList',
  templateUrl: './recipeList.component.html',
  styleUrls: ['./recipeList.component.css']
})

export class RecipeListComponent {
  buttonNew = "New Recipe";

  Items: ListItem[] = [
    { Title: 'Chocolate Cake' },
    { Title: 'RoastBeaf' }
  ];

  RecipeTitle:string;

  whenClicked = false;

  ChangeColor(){
      this.whenClicked = true;
  }

  addToList(){
    this.Items.push({Title: this.RecipeTitle})
  }
}

class ListItem{
  Title: string;
}

Solution

  • You can track one by one li tags for clicked status:

    HTML

        <ul class="list-group col-lg-6">
            <li href="#" class="list-group-item" (click)="whenClicked[i]=!whenClicked[i]" 
                  [style.background-color] = "whenClicked[i]  ? 'blue' : 'green'" 
                  *ngFor="let recipe of Items ; let i = index;trackBy: tracked">
                  {{recipe.Title}}</li>
        </ul>
    

    Typescript

      whenClicked = [false,false];
    

    Stackblitz Demo

    If you don't wish to put back the color, then ...(click)="whenClicked[i]=true" ... is enough.