【发布时间】:2017-02-09 03:27:07
【问题描述】:
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() 将所选项目的背景颜色更改为黄色。截至目前,所有列表项的颜色都在变化。在我的示例中,我没有了解如何仅为选定的英雄专门更改颜色。你能告诉我我哪里出错了。
【问题讨论】:
-
为什么不将 CSS 添加到您的组件中,以解决您已经添加的
selected类?
标签: angular