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:
 

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


app.component.ts:
 

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:Before clicking on any item:



After clicking on any item:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.