【问题标题】:how to use angular material form field and flex-layout如何使用角度材质表单域和 flex-layout
【发布时间】:2019-10-11 15:44:22
【问题描述】:

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

这是一个完整的stack-blitz example

当您启动应用程序时,我们会看到这个

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

无论如何。主要问题是 第二个字段没有像预期的那样缩小。 180px以下不会缩小:

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

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

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

使用此解决方法,第二个输入按预期缩小:

::ng-deep is deprecated 将被删除。
那么什么是正确的方法让输入按预期缩小?

【问题讨论】:

    标签: angular-flex-layout angular-material-7


    【解决方案1】:

    由于 .mat-form-field-infix 的固定宽度为 180 像素,因此无法将表单字段缩小到 180 像素以上。不可避免地 .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>
    

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

    【讨论】:

    • link 到一个有关视图封装的相关问题,以回答为什么全局 styles.scss 中的相同 css 与 component.scss 中的工作方式不同
    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 2016-01-19
    • 2019-03-04
    • 2022-10-05
    • 1970-01-01
    • 2019-06-14
    • 2019-06-09
    • 2017-11-22
    相关资源
    最近更新 更多