Open In App

How to change the list item bg-color individually using ngFor in Angular 2+ ?

Introduction:
We can solve this using *ngFor directive and attribute binding for binding the background colour.

    Approach:

  1. Using *ngFor directive iterate through a list of items in .html file.
  2. By using attribute binding, bind the background color for every item in the list.
  3. By default use an array which consists of false boolean value in .ts file.
  4. Use a on click event handler to toggle the background color of the item in the list.
  5. Once the implementation is done then serve the project using below command.
    ng serve --open

Implementation by code:
app.component.html:
 




<ul>                        
                                                              
    <li  (click)="changeColor[i]=!changeColor[i]"  
// we are toggling the background 
// colour on click event handler
   [style.background-color] = "changeColor[i]  ? 'red' : 'green'" 
   *ngFor="let item of list ; let i = index">
      {{item.name}}
    </li>
    
</ul>

app.component.ts:
 






import { Component } from '@angular/core';
  
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  
changeColor= [false, false, false];
  
list = [
    { name : 'GeeksForGeeks' },
    { name : 'Google' },
    { name : 'HackerRank'}
  ];
}

Output:Before clicking on any item:

After clicking on any item:


Article Tags :