【问题标题】:How to change the background colour of md-card based on some condition in angular 2?如何根据角度 2 中的某些条件更改 md-card 的背景颜色?
【发布时间】:2017-10-16 14:22:41
【问题描述】:

我通过 *ngFor 循环动态显示卡片。我想根据某些条件更新卡片背景颜色。例如如果满足某些条件,则卡片背景为绿色。否则,卡片背景颜色不变或变为红色。如何在 Angular 2 中实现这种动态行为?我尝试使用 *ngIf,但后来布局搞砸了。我只想根据条件更改背景颜色而不影响任何布局更改。对于响应式行为,我使用的是 flex 布局。

<div fxLayout="row" fxLayoutWrap style="padding-bottom: 25px; 
                                        padding-top: 25px;
                                        margin: auto;
                                        justify-content: center">  
    <md-card fxFlex.gt-md="45" 
             fxFlex.md="45" 
             fxFlex.sm="auto" 
             fxFlex.xs="100" 
             *ngFor="let data of myArray"
             [style.background]="'lightBlue'"
              style="margin:5px;">

        <md-card-content>
            <h1></h1>
            <h2></h2>
            <h2></h2>
        </md-card-content>
    </md-card> 
</div>

【问题讨论】:

  • 试试下面的表达式:[ngStyle]="{backgroundColor: data.property === 'something' ? 'green' : 'red'}"
  • @Lambo14 非常感谢...成功了
  • @Lambo14 如何修改上述表达式以使同一属性具有三个条件。例如 data.property > 'something' 将颜色设置为蓝色,data.property
  • 使用三元运算符两次,即 [ngStyle]="{backgroundColor: data.property > 'something' ? 'blue' : (data.property

标签: css angular material-design angular-material2


【解决方案1】:

这也很有效[style.background]="condition ? 'lightBlue':'yellow'"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 2018-07-29
    相关资源
    最近更新 更多