首页 > 解决方案 > Mat-form-field - 失焦时的样式和 mat-input 中的文本

问题描述

当 mat-input 中有文本同时失焦时,我怎样才能使失焦样式不适用?

我想在失焦和带有文字的情况下保留这些样式:

在此处输入图像描述

但现在这是我在失焦和文字时得到的结果:

在此处输入图像描述

此外,当没有文本且失焦时,该字段的外观如下:

在此处输入图像描述

我现在的风格:

.mat-form-field-appearance-outline .mat-form-field-outline {
    background-color: #FFFFFF66;
    border-radius: 10em;
    color: transparent;
    opacity: 0.5;
}

.mat-form-field-appearance-outline.mat-focused .mat-form-field-outline-thick {
    color: white;
    background-color: transparent;
}

先感谢您。

标签: angularangular-materialmat-form-field

解决方案


我在评论中看到您已经注意到 Angular 删除了mat-focused该类,因此mat-form-field直接将其应用于该类是行不通的。但是,我们应该能够将类应用到将匹配“focused”样式的包装容器。

  • div.mat-form-field-outline嵌套在具有mat-form-field-appearance-outlinemat-focused 类的元素中时具有“重点”规则

  • mat-label当嵌套在具有mat-form-fieldmat-focused类的元素中时,该元素具有“聚焦”规则。

因此,我们可以为容器提供mat-form-field-appearance-outline和类,并根据表单字段值切换类。mat-form-fieldmat-focused

<p>
  <span
    class="mat-form-field mat-form-field-appearance-outline"
    [ngClass]="{'mat-focused': field.value}"
  >
    <mat-form-field appearance="outline">
      <mat-label>Outline form field</mat-label>
      <input #field matInput placeholder="Placeholder" />
      <mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
      <mat-hint>Hint</mat-hint>
    </mat-form-field>
  </span>
</p>

https://stackblitz.com/edit/angular-ckvs4z?file=src/app/form-field-appearance-example.html


推荐阅读