首页 文章

Angular / Material中的样式mat-form-field输入

提问于
浏览
6

我有一个带有输入的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;
}

2 回答

  • 1

    根据我的理解,这两个功能似乎都在MatFormField中 .

    不推荐使用

    • floatPlaceholder,因为它现在是FloatLabelType( 'never', 'always', 'auto' )的 [floatLabel] ,使用输入应用

    • 您可以使用输入 [color] 更改下划线的颜色,但是您只能从主题中选择颜色( 'primary', 'accent', 'warn' ) . 有关如何设置主题的更多信息,请转至their website here

    <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>
    
  • 2

    您可以使用下面使用的css选择器:

    /deep/ .mat-input-underline {
       background-color: white;
    }
    

    /deep/ combinator is slated for deprecation in Angular ,所以没有它最好 . 不幸的是,Angular Material的.mat-input-underline是高度指定的,这使得很难在不使用/ deep /的情况下覆盖

    我发现的最好方法是使用ID,与默认的Angular Material样式相比,它允许您更高的特异性 .

    <form id="search-form" [formGroup]="form" (ngSubmit)="submit()">
        <mat-form-field>
          <mat-placeholder class="placeholder">Search</mat-placeholder>
          <input type="text" class="toolbar-search" matInput formControlName="search">
          <mat-icon matSuffix>search</mat-icon>
        </mat-form-field>
    

    然后,您的“搜索表单”ID可用于定位输入 . 在不破坏视图封装的情况下,您无法在component.scss中定位mat-form-field-underline . 通过将此添加到global.scss,可以更轻松地在全局级别执行此操作

    global.scss:

    #search-form {
      .mat-form-field-underline {
        background-color: $accent;
      }
      .mat-form-field-ripple {
        background-color: $accent;
      }
      .placeholder {
        display: none;
      }
    }
    

    我希望Angular Material团队在未来能够恢复他们的特异性,因为目前没有简单的方法来覆盖他们的默认值 .

相关问题