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