如何更改从列表中选择的项目的背景颜色?

时间:2017-02-08 19:16:43

标签: angular

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()将所选项目的背景颜色更改为黄色。截至目前,它改变了所有列表项的颜色。我没有得到如何仅在我的示例中为selectedhero专门更改颜色。能告诉我你哪里出错了吗?

1 个答案:

答案 0 :(得分:6)

<p [style.background-color]="getStyle(hero)">

    getStyle(hero) {
        if (hero === this.selectedHero) {
            return "grey";
        } else {
            return "";
        }
    }

<p [style.background-color]="hero===selectedHero ? 'grey' : ''">