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 "";
}
}
}
我想更改从列表中选择的项目的背景。根据我上面的代码,我有一个列表,我正在尝试调用方法 getStyle() 将所选项目的背景颜色更改为黄色。截至目前,所有列表项的颜色都在变化。在我的示例中,我不知道如何专门更改所选英雄的颜色。你能告诉我哪里出错了吗?
最佳答案
<p [style.background-color]="getStyle(hero)">
getStyle(hero) {
if (hero === this.selectedHero) {
return "grey";
} else {
return "";
}
}
或
<p [style.background-color]="hero===selectedHero ? 'grey' : ''">
关于angular - 如何更改从列表中选择的项目的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42121765/