【问题标题】:How to apply two different CSS on mat-form-field in separate pages?如何在不同页面的 mat-form-field 上应用两个不同的 CSS?
【发布时间】:2020-08-06 09:23:45
【问题描述】:

我在一页上有 mat-form-field:-

<mat-form-field class="form-control-full-width">
    <input type="text" matInput placeholder="First Name"  formControlName="firstNameFC" required>            
    <mat-error *ngIf="hasNewUserError('firstNameFC', 'required') && isNewUserSubmitted">
               First Name is required
    </mat-error>
</mat-form-field> 

以下 CSS 应用:-

 .mat-form-field-label {
    /*change color of label*/
    color: white !important;
  }

  .mat-form-field-underline {
    /*change color of underline*/
    background-color: white !important;
  } 

  .mat-form-field-ripple {
   /*change color of underline when focused*/
    background-color: white !important;;
  }

  .mat-input-element{
    color: white !important;
  }

CSS 正在按预期进行反射。

问题是我在不同的页面上有另一个 mat-form-field 并且想在该字段上应用不同的 CSS(颜色:绿色,背景颜色:白色)。

是否可以在不同页面的控件上应用不同的 CSS?

【问题讨论】:

    标签: html css angular angular-material mat-form-field


    【解决方案1】:

    是的,它可能只是创建一个名为 textfield.css

    的单独文件

    将其导入您的 style.css 之类的

    @import 'globalcss/textfield.scss';
    

    将该文件放在 globalcss 文件夹中,使该文件夹在 src 下

    src=>globalcss=>textfield.scss

    现在您可以使用任何 matInput 并添加类似 small-text-field 的样式,请参阅下面添加的类

     <mat-form-field class="small-text-field"> 
                  <input matInput placeholder="Username">
                </mat-form-field>
    

    textfield.css 文件中的内容是这样的

    .mat-form-field.smallTextfield .mat-form-field-wrapper{
        font-size: 10px;
        width: 125px;
    }
    

    所以在整个应用程序中,无论你有 matInput,如果你应用这个类,它就会被添加,但请注意,现在 ng::deep 已被弃用,使用 ts 文件中的以下指令作为

    封装:ViewEncapsulation.None

    这将在内部使用

    @Component({selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css'],
    encapsulation: ViewEncapsulation.None})
    

    我希望这是更好更清晰的解释也很容易理解..!!

    【讨论】:

      【解决方案2】:

      是的,您可以像这样将它们添加到每个组件的 css 文件中:

      :host ::ng-deep .mat-form-field-label {
          color: white;
      }
      

      【讨论】:

      • 谢谢。我理解你的方法,但无法得到结果。我正在使用 style.css。现在我删除了这些行并添加到 login.component.css 文件中。我还添加了 styleUrls: ['./login.component.css'] 但它没有反映 CSS。知道为什么它不起作用吗?还有什么事情要做吗?
      猜你喜欢
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2011-02-11
      • 2019-02-05
      • 2020-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多