Introduction:
We can solve this using *ngFor directive and attribute binding for binding the background colour.
-
Approach:
- Using *ngFor directive iterate through a list of items in .html file.
- By using attribute binding, bind the background color for every item in the list.
- By default use an array which consists of false boolean value in .ts file.
- Use a on click event handler to toggle the background color of the item in the list.
- 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: