TmT*_*ron 1 angular-flex-layout angular-material-7
我想在一行中有 2 个表单输入字段:1. 第一个有固定的,1. 第二个应该增长和缩小,但这不会缩小到 180px 以下。
这是一个完整的堆栈闪电战示例
有可能另一个问题:
我认为第二个输入字段应该已经显示提示文字和水平线-但它只会显示它时,它得到的焦点。
这是预期的行为还是我错过了什么?
反正。主要问题是第二个字段没有按预期缩小。它不会缩小到 180 像素以下:

在 chrome dev-tool 中,我可以看到input元素用 a 包裹,div class="mat-form-field-infix">并且类mat-form-field-infix的宽度固定为 180px!
我想出的唯一解决方法是使用 using 覆盖此宽度::ng-deep。
您可以在 Stackblitz 示例的co-input-field.component.scss文件中激活它
:host ::ng-deep .mat-form-field-infix {
// width: auto !important;
width: unset !important;
}
Run Code Online (Sandbox Code Playgroud)
但是::ng-deep 已被弃用并将被删除。
那么使输入按预期缩小的正确方法是什么?
由于 .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 {}
Run Code Online (Sandbox Code Playgroud)
然后在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
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
3.不要禁用视图封装。为这种特殊情况定义一个全局规则。
将以下内容放入 styles.scss
.shrinking-mat-form-field {
.mat-form-field-infix {
width: auto !important;
}
}
Run Code Online (Sandbox Code Playgroud)
并将.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>
Run Code Online (Sandbox Code Playgroud)
尽管第二种和第三种方法基本相同,但我个人更喜欢第三种方法,以使其具有可读性,在整个项目中保持一致,将副作用降至最低并从一个点进行管理。
| 归档时间: |
|
| 查看次数: |
2665 次 |
| 最近记录: |