import { Component } from '@angular/core';
export class Hero {
name: string;
}
const HEROES: Hero[] = [
{ name: 'STWX1' },
{ name: 'STWX2' },
{ name: 'STWX3' },
{ name: 'STWX4' }
];
@Component({
selector: 'my-app',
template: `
<div style="display: inline-block; width = 200px; ">
<ul class="heroes">
<li *ngFor="let hero of heroes" (click)="onSelect(hero)"
[class.selected]="hero === selectedHero">
<p [style.background-color]="getStyle()">{{hero.name}}</p>
</li>
</ul>
</div>'
,
styles: [...]
})
export class AppComponent {
public showStyle: boolean = false;
name = 'Angular1';
testRequestId = '3224';
heroes = HEROES;
selectedHero: Hero;
goToDivClick() {
return HEROES;
}
onSelect(hero: Hero): void {
this.showStyle = true;
this.selectedHero = hero;
}
getStyle() {
if (this.showStyle) {
return "grey";
} else {
return "";
}
}
}
I want to change the background of the item selected from a list. As per my code above, I have a list and I am trying to call a method getStyle() to change the background color of the selected item to Yellow. As of now, its changing color for all the list items. I am not getting how to specifically change color only for the selectedhero in my example. Can you please let me know where am I going wrong.
To add background color in HTML, use the CSS background-color property. Set it to the color name or code you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a table, heading, div, or span tag.
Select Start > Settings > Personalization > Colors, and then choose your own color, or let Windows pull an accent color from your background.
Press the Windows key , type Settings, and then press Enter . In the Settings window, select the Personalization option from the left navigation menu. On the right side of the window, click the Background option.
Use any of the . bg-color classes to add a background color to the navbar. Tip: Add a white text color to all links in the navbar with the . navbar-dark class, or use the .
<p [style.background-color]="getStyle(hero)">
getStyle(hero) {
if (hero === this.selectedHero) {
return "grey";
} else {
return "";
}
}
or
<p [style.background-color]="hero===selectedHero ? 'grey' : ''">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With