MetaDude
MetaDude

Reputation: 149

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;
}

Upvotes: 2

Views: 4370

Answers (2)

Vega
Vega

Reputation: 28708

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.

Upvotes: 3

pbalaga
pbalaga

Reputation: 2068

This is because the whenClicked variable is shared by all items in the list. You need to store state for every item separately. (Move click handler and whenClicked to the item object.) Something along these lines:

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

To color on hover only, you can do it with css solely: https://codepen.io/pbalaga/pen/zEKgwP

Upvotes: 0

Related Questions