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()方法将所选项目的背景色更改为Yellow。到目前为止,所有列表项的颜色都在变化。在我的示例中,我没有获得如何仅为所选英雄专门更改颜色的方法。你能告诉我我要去哪里了吗?
<p [style.background-color]="getStyle(hero)">
getStyle(hero) {
if (hero === this.selectedHero) {
return "grey";
} else {
return "";
}
}
要么
<p [style.background-color]="hero===selectedHero ? 'grey' : ''">
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句