【问题标题】:How to change the background color of the item selected from the list?如何更改从列表中选择的项目的背景颜色?
【发布时间】: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


【解决方案1】:
<p [style.background-color]="getStyle(hero)">

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

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

【讨论】:

  • 非常感谢,它运行良好。另外,如果列表增长,请告诉我如何在这种情况下保持 div 高度固定。我的意思是当列表增长时,我想显示滚动条,而不是扩展 div 高度。
  • 如果您只需要垂直滚动条,只需设置您想要的heightoverflow: autooverflow: scrolloverflow-y: auto
  • 我的 CSS 是这样的。 .container .col { 显示:表格单元;宽度:25%;高度:200px;边框颜色:红色;边框样式:山脊;溢出:自动; }
  • 你是用scroll而不是auto吗?
  • 很难说。 Angular2 没有什么特别之处,这就是它在 CSS 中的实现方式
猜你喜欢
  • 2021-02-06
  • 1970-01-01
  • 2011-01-09
  • 1970-01-01
  • 1970-01-01
  • 2017-09-30
  • 2023-01-01
  • 1970-01-01
相关资源
最近更新 更多