在 Angular/Material 中设置 mat-form-field 输入样式

新手上路,请多包涵

我有一个带有输入的 mat-form-field,我想向其中添加自定义样式,但是我在 Angular Material 官方网站上找不到任何关于此的文档。

我的最终目标是:

  • 选择输入框后更改下划线颜色
  • 删除浮动标签(如果可能 - 我知道这是一项功能,但现在已弃用)。

我还不是最擅长 Angular,但是如果需要在 JS 中进行更改,那么我总是可以尽我所能。

我只需要一点指导。

当前代码:

 <form class="search-form">
  <mat-form-field class="example-full-width">
    <input class="toolbar-search" type="text" matInput>
    <mat-placeholder>Search</mat-placeholder>
    <mat-icon matSuffix style="font-size: 1.2em">search</mat-icon>
  </mat-form-field>
</form>

当前的 CSS:

 // Change text colour when inputting text
.toolbar-search, mat-placeholder {
  color: white;
}

// Changes the underline and placeholder colour before input is selected
/deep/ .mat-input-underline {
    background-color: white;
}

原文由 physicsboy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

据我了解,这两个功能似乎都在 MatFormField 中。

  1. floatPlaceholder 已弃用,因为现在它是 [floatLabel] 用于 FloatLabelType ( 'never', 'always', 'auto' ),使用输入应用
  2. 您可以通过输入 [color] 更改下划线的颜色,但是您只能从主题中选择颜色( 'primary', 'accent', 'warn' )。有关如何设置主题的更多信息,请访问 他们的网站
 <form class="search-form">
  <mat-form-field class="example-full-width"
                  floatLabel="never" color="primary">
    <input class="toolbar-search" type="text" matInput placeholder="search">
    <mat-icon matSuffix style="font-size: 1.2em">search</mat-icon>
  </mat-form-field>
</form>

原文由 Iancovici 发布,翻译遵循 CC BY-SA 3.0 许可协议

要使用 scss 更改材质输入的样式:

标准:

 ::ng-deep .mat-form-field {
    .mat-input-element {
        color: slategray;
    }
    .mat-form-field-label {
        color: slategray;
    }
    .mat-form-field-underline {
        background-color: slategray;
    }
    .mat-form-field-ripple {
        background-color: slategray;
    }
    .mat-form-field-required-marker {
        color: slategray;
    }
}

重点:( 选中时)

 ::ng-deep .mat-form-field.mat-focused {
    .mat-form-field-label {
        color: #ff884d;
    }
    .mat-form-field-ripple {
        background-color: #ff884d;
    }
    .mat-form-field-required-marker {
        color: #ff884d;
    }
    .mat-input-element {
        color: #ff884d;
    }
}

无效的:

 ::ng-deep .mat-form-field.mat-form-field-invalid {
    .mat-input-element {
        color: #ff33cc;
    }
    .mat-form-field-label {
        color: #ff33cc;
        .mat-form-field-required-marker {
            color: #ff33cc;
        }
    }
    .mat-form-field-ripple {
        background-color: #ff33cc;
    }
}

演示

您还可以使用 ViewEncapsulation.None 来避免 ::ng-deep弃用

 import { ViewEncapsulation } from '@angular/core';

@Component({
    ...
    encapsulation: ViewEncapsulation.None
})

原文由 A. Morel 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题