css - Angular Material 13 - 如何更改 mat-form-field 边框的颜色

标签 css angular angular-material

如何更改 mat-form-field 边框的颜色? (选择字段时的边框) 谢谢^^ screen

.search {
  display: flex;
  justify-content: center;
  margin-top: 1%;
  mat-form-field {
    width: 70%;
  }
}
<form class="search">
  <mat-form-field appearance="outline">
    <mat-label>Search</mat-label>
    <input matInput>
    <mat-icon matSuffix>search</mat-icon>
  </mat-form-field>
</form>

最佳答案

正确的方法是为表单字段定义一个新的主题。主题由主调色板、辅助调色板和可选的警告调色板(默认为红色)组成。

node_modules/@angular/material/core/theming 中有许多预定义的调色板,但您也可以定义自己的调色板。

在下面的示例中,我为 search 类下的所有表单字段指定了橙色和黄色主题。

@use "@angular/material" as mat;

$my-primary: mat.define-palette(mat.$orange-palette);
$my-accent: mat.define-palette(mat.$yellow-palette);

$my-theme: mat.define-light-theme(
  (
    color: (
      primary: $my-primary,
      accent: $my-accent,
    ),
  )
);

.search {
  @include mat.form-field-theme($my-theme);
}

这一行:@include mat.form-field-theme($my-theme);返回更改表单字段主题所需的所有CSS。每个 Material 组件都有一个这样的函数,您可以在 node_modules/@angular/material/_index.scss

中看到它们被导出

注意:此 scss 需要是全局的,因此您需要将其放入全局样式文件中,例如 styles.scss

或者,您可以通过禁用 View 封装来使组件的 scss 全局化。

@Component({
  ...
  encapsulation: ViewEncapsulation.None,
})
export class MyComponent {
  ...
}

更多信息:https://material.angular.io/guide/theming


作为一个快速技巧,您还可以像这样覆盖 css:

只是边框

.search
  .mat-form-field-appearance-outline.mat-focused
  .mat-form-field-outline-thick {
  color: red;
}

还有标签

.search {
  .mat-form-field-appearance-outline.mat-focused .mat-form-field-outline-thick {
    color: red;
  }

  .mat-form-field.mat-focused .mat-form-field-label {
    color: red;
  }
}

开发人员不建议像这样覆盖 css,因为它在以后的版本中很容易出现问题:https://material.angular.io/guide/customizing-component-styles

关于css - Angular Material 13 - 如何更改 mat-form-field 边框的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72134233/

相关文章:

javascript - 了解为什么这个导入变量的字符串插值在我的 Angular 2 应用程序中起作用

javascript - ng如果不更新 DOM

android - ionic 键盘和 ngIf 未按预期工作

AngularJS - 如何在 2016 年开始最好?

Angular 子路由,嵌套路由器 socket

css - 同步 CSS 关键帧颜色动画

css - 如何在页面中心显示用户登录包括所有控件?

css - Angular Material 和 Flex 布局 - 设置并排和多行响应图像

javascript - 将一个元素的 x y 坐标与元素列表进行比较以找到匹配项 (jQuery)

html - 防止居中布局在出现滚动条时移动其位置