如何自定义`mat-form-field`

时间:2019-06-18 16:33:26

标签: angular-material

我正在尝试使用mat-form-field覆盖::ng-deep .mat-form-field**样式。但我读到它将很快过时。

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

在我的情况下,由于我需要使用表单中的密集字段并且使用提示填充会增加滚动条,因此我降低了高度并删除了底部的额外填充以获取提示。

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

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

::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吗?

1 个答案:

答案 0 :(得分:1)

我看到物料小组将类似dense的属性用于物料清单。因此,您可以在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官方文档;)