【问题标题】:How to apply angular material style properties based on some conditions?如何根据某些条件应用角度材质样式属性?
【发布时间】:2020-10-27 14:37:16
【问题描述】:

我有一个枚举叫做 status as

export const enum Status {
    ACTIVE = "Active",
    REVIEW = "Review"
}

我有一个类似的垫子按钮

<button class="status-button"
                 mat-raised-button  color="warn">{{myObj.realStatus}}</button>

status-button 是我自己的班级和 颜色是棱角材质的属性。

我想要两种基于枚举改变颜色的方法

喜欢

  1. 如果 Enum 处于活动状态,我想要颜色警告 else 主要(即我想根据从 myObj 获得的枚举条件更改 mat 按钮的颜色属性)

  2. 如果我可以同时添加两个基于 Enum 的类,这是附加样式以及 status-button

我怎样才能以更简单的方式实现这一点希望我的问题很清楚..!!

【问题讨论】:

  • 这里有类似的问题,可以借鉴一下。 stackoverflow.com/questions/53496808/…
  • @Kiril 我认为这里使用的 css 是自定义 css 我需要为材料 UI 组件属性应用条件不需要外部 css 评估
  • 我已经修改了我的答案..请检查..

标签: angular angular-material angular8


【解决方案1】:
  1. 为此,请在打字稿中实现以下内容:
public colorPicked: string = Status.ACTIVE? "warn" : "primary"

接下来在 HTML 中将颜色替换为您创建的新变量:

button class="status-button"
                 mat-raised-button  color="colorPicked">{{myObj.realStatus}}</button>
  1. 第二个,如果我理解正确的话,你想改变基于枚举的 CSS 类。您可以使用 NgClass 根据表达式选择类(class1 和 class2 是在 css 文件中定义的 css 类):
button [ngClass]="{'class1': Status.ACTIVE, 'class2': Status.REVIEW}">{{myObj.realStatus}}</button>

【讨论】:

  • 嗯,在第一种情况下,我想直接在 html 中解决问题,比如检查 myObj.realStatus 是否它的活动将应用主要的,否则警告是否可能?因为我不需要为样式创建额外的变量
  • 我刚刚尝试评估表达式并且它在场外被正确评估我们无法到达那里枚举,但我们可以像这样检查,但任何想法如何将此条件用于颜色属性?
  • 关于1),是的,您可以避免使用变量并直接在html中传递条件。
  • 我只是用了这个,但是颜色没有拾取,没有错误你能帮我看看这里做错了什么吗?
  • 更正:
【解决方案2】:

试试这个:

 <button mat-raised-button
        class="status-button"
        [ngClass]="myObj.realStatus == 'Active' ? 'activeClass' : 'reviewClass'">
        {{myObj.realStatus}}
</button>

由于您是基于枚举提供颜色和 css 文件,因此您还可以将 background-color 属性添加到 css 类中,从而避免来自 html 的颜色属性。

.css

.activeClass {
  color: black;
  background-color: #f44336;  /*warn*/
}

.reviewClass {
  color: white;
  background-color:#3f51b5;  /*primary*/
}

【讨论】:

  • 嗯,在第一种情况下,我想直接在 html 中解决问题,比如检查 myObj.realStatus 是否它的活动将应用主要的,否则警告是否可能?因为我不需要为样式创建额外的变量
  • 我刚刚尝试评估表达式并且它在场外被正确评估我们无法到达那里枚举,但我们可以像这样检查,但任何想法如何将此条件用于颜色属性?
【解决方案3】:

如果我理解正确,您想根据条件更改颜色。要到达那里,您可以使用 ngClass 和 ngStyle 指令。

例如:

在你的 component.html 中

<button [ngClass]="{'defaultClass': true,
                'redClass': condition1 // (ACTIVE),
                'greenClass': condition2  // (REVIEW)}"
    [ngStyle]="{color: getColor()}">
</button>

在您的 component.ts 中

getColor() {
    if (condition1) {
      return 'green';
    } else if(condition2) {
      return 'red';
    }
  }

在您的 component.css 中

.defaultClass{ 
// Your default style
}
.red{ 
// Your style
}

.green{ 
// Your style
}

【讨论】:

    猜你喜欢
    • 2016-01-11
    • 1970-01-01
    • 2019-04-05
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 2015-12-11
    相关资源
    最近更新 更多