【问题标题】:Conditionally applying css to mat form field有条件地将 css 应用于 mat 表单字段
【发布时间】:2020-08-02 01:05:17
【问题描述】:

我正在开发一个 Angular 应用程序,并且我正在其中使用 mat 表单字段。为了更改 mat 表单字段底部边框的颜色,我正在使用 mat-form-field-ripple css,它是为 mat 表单字段内置的。 CSS如下。

.mat-form-field-ripple {
    background-color: #f9c940!important;
}

当我使用这个 CSS 时,它会自动应用于所有表单字段。当一个条件为真时,我必须在 mat-form-filed-ripple 中应用#f9c940 颜色,而当另一个条件为真时应用不同的颜色。我的mat表单域代码如下:

                        <mat-form-field appearance="fill">
                            <mat-label [ngClass]="{}">Name</mat-label>
                            <input formControlName="Name" readonly>
                        </mat-form-field>

我试图使用 ngClass 来完成它,但没有得到它。我该怎么做?

【问题讨论】:

  • 我只是举了一个例子。任何了解 Angular 的人都知道它的作用。只是想解释我在尝试什么

标签: css angular angular-material angular7 angular8


【解决方案1】:

只需创建自己的 CSS 类:

.mat-form-field-ripple {
    //your standard styling,
}

.myBackgroundColor {
    background-color: #f9c940!important;
// add this selector below the .mat-form-field-ripple selector so that it will override..
}

然后有条件地将其应用于您的标签:

<mat-form-field appearance="fill">
    <mat-label [ngClass]="{'myBackgroundColor': mycheck}">Name</mat-label>
    <input formControlName="Name" readonly>
</mat-form-field>

在您的组件中,您有它所基于的表达式:

mycheck = true; // you will modify this true to any expression that is transformable to a boolean. If true, your class is applied, if false then not..

【讨论】:

  • 我如何在这个中使用 mat-form-field-ripple?有条件地
  • @zaib7777 您可以使用 CSS 中的 .mat-form-field-ripple 选择器应用您的一般样式。但是您有时想要的颜色不在该选择器中(因为这将适用于所有元素),而是在另一个选择器中,您可以有条件地将其应用于您的字段以覆盖一般样式。我已经更新了我的答案给你看
【解决方案2】:

您可以像这样有条件地应用类:

<mat-label [ngClass]="{'your-class': foo=='foo', 'your-class-another':bar=='bar' }">
    Name
</mat-label>

【讨论】:

  • nops 正常的 ngClass 条件在此不起作用。已经试过了
  • @zaib7777 你能创建一个 stackblitz 示例吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-07
  • 2020-09-09
  • 2012-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多