【问题标题】:How to customize `mat-form-field`如何自定义`mat-form-field`
【发布时间】:2019-06-18 16:33:26
【问题描述】:

我正在尝试使用::ng-deep .mat-form-field** 覆盖mat-form-field 样式。但我读到它很快就会被弃用。

我使用::ng-deep 覆盖了一些样式,它部分解决了我的需求。但我也想在某些情况下使用默认的mat-form-field

在我的情况下,我降低了高度并移除了底部的额外填充以作为提示,因为我需要在表单中使用密集字段并且提示填充会添加滚动条。

但我有一些对话框可以使用默认的 mat-form-field 并像平常一样使用 mat-hint

我在scss 文件中有以下样式,我使用@import 将此文件导入我的组件scss

::ng-deep .mat-form-field-flex > .mat-form-field-infix { padding: 0.4em 0px !important;}
::ng-deep .mat-form-field-label-wrapper { top: -1.5em;}

::ng-deep .mat-form-field-appearance-outline.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label {
    transform: translateY(-1.1em) scale(.75);
}

::ng-deep .mat-form-field-wrapper{
    padding-bottom: 0;
}

有人可以建议一种能够同时使用这两种样式的方法,例如扩展 mat-form-field 并在申请我的密集表单时对其进行自定义,并在其他地方通常使用mat-form-field

【问题讨论】:

    标签: angular-material


    【解决方案1】:

    我看到 Material Team 使用 dense 之类的属性作为 mat-lists。因此,您可以在 styles.scss 中进行全局自定义,例如:

    .mat-form-field[dense] {
      .mat-form-field-flex > .mat-form-field-infix {
        padding: 0.4em 0px !important;
      }
      .mat-form-field-label-wrapper {
        top: -1.5em;
      }
      &.mat-form-field-appearance-outline.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label {
        transform: translateY(-1.1em) scale(.75);
      }
      .mat-form-field-wrapper{
        padding-bottom: 0;
      }
    }
    

    只需将属性添加到您的字段中:

    <mat-form-field dense ...
    

    这种属性可以被认为是“组件变体”,一些 CSS 方法建议为它定义一个类,如.mat-form-field-dense,但我更喜欢属性方法:)

    编辑:如果你想在你的组件中包含这种deep 自定义,你需要禁用封装,包括:

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

    这将告诉 Angular 不要使用封装样式的属性来标记您的组件样式,以便仅与您的组件元素一起使用,而不会干扰其他组件的子元素。如果你想知道它是如何工作的,请参考 Angular Styles 官方文档;)

    【讨论】:

    • 这就是我想要的。如果我包含在styles.scss 中,它会起作用。但如果我将它包含在我的组件 scss 中,则不适用。
    • @rainversion_3 我刚刚编辑了答案以包含该信息:) 祝你有美好的一天
    猜你喜欢
    • 2020-10-26
    • 2019-06-18
    • 2018-04-16
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多