1

我想在一行中有2个表单输入字段:1.第一个有一个固定的,1.第二个应该增长和缩小,但这不会缩小到180px以下。

这是一个完整的堆栈闪电战示例

当您启动应用程序时,我们会看到
在此处输入图像描述

可能还有另一个问题
我认为第二个输入字段应该已经显示提示文本和水平线 - 但它只会在获得焦点时显示。
这是预期的行为还是我错过了什么?

反正。主要问题是第二个字段没有按预期缩小。它不会缩小到 180px 以下:
在此处输入图像描述

在 chrome 开发工具中,我可以看到input元素用 a 包裹,div class="mat-form-field-infix">并且类mat-form-field-infix的固定宽度为 180px!

我想出的唯一解决方法::ng-deep是用 using 覆盖这个宽度。
您可以在 Stackblitz 示例的co-input-field.component.scss文件中激活它

:host ::ng-deep .mat-form-field-infix {
  // width: auto !important;
  width: unset !important;
}

使用此解决方法,第二个输入按预期缩小:
在此处输入图像描述

但是::ng-deep 已被弃用并将被删除。
那么让输入按预期缩小的正确方法是什么?

4

1 回答 1

5

由于 .mat-form-field-infix 具有 180px 的固定宽度,因此无法使表单域缩小到 180px 以上。不可避免地 .mat-form-field-infix 必须被覆盖。

您可以通过以下几种方式使用 ::ng-deep 获得相同的结果;

1.禁用该特定组件的视图封装。但是,这种方法有一个巨大的缺点,即组件中的所有样式都变成了全局样式,因此需要仔细管理它们。

@Component({
    selector: 'app-co-input-field',
    templateUrl: './co-input-field.component.html',
    styleUrls: ['./co-input-field.component.scss'],
    encapsulation: ViewEncapsulation.None
})
export class CoInputFieldComponent {}

然后在co-input-field.component.scss你做以下

app-co-input-field {
    .mat-form-field-infix {
      width: auto !important;
    }
    // all other component styles goes in here
    // in order to keep them isolated from global scope
}

2.不要禁用视图封装。在全局样式中使用父组件的元素选择器。

将以下内容放入styles.scss

app-co-input-field {
    .mat-form-field-infix {
      width: auto !important;
    }
    // co-input-field.component.scss still can be used for encapsulated styles
}

3.不要禁用视图封装。为这种特殊情况定义一个全局规则。

将以下内容放入styles.scss

.shrinking-mat-form-field {
    .mat-form-field-infix {
      width: auto !important;
    }
}

并将.shrinking-mat-form-field类应用于相应的元素

<mat-form-field style="width: 100%" class="shrinking-mat-form-field">
  <input matInput placeholder="placeholder"  />
  <mat-hint align="end">hint text</mat-hint>
</mat-form-field>

尽管第二种和第三种方法基本相同,但我个人更喜欢第三种方法,以使其具有可读性,在项目中保持一致,具有最小的副作用并从单点管理它们。

于 2019-06-02T13:29:52.843 回答