[英]Angular Material: Styling mat-form-field inside mat-toolbar
我正在尝试使用 Material 的mat-toolbar
创建一个工具栏,其中包含一个输入和 select。 对于两者,我按照建议在mat-form-field
中使用 Material 提供的组件(分别为mat-input
和mat-select
)。 我的代码如下所示:
<mat-toolbar>
<mat-form-field appearance="outline">
<mat-icon matPrefix>search</mat-icon>
<input type="search" matInput placeholder="Search" />
</mat-form-field>
<mat-form-field appearance="outline">
<mat-select [(value)]="omitted">
<mat-option *ngFor="let omitted of omitted" [value]="omitted.slug">
{{ omitted.name }}
</mat-option>
</mat-select>
</mat-form-field>
</mat-toolbar>
目前,input 和 select 太高,无法完全放入工具栏。 我正在尝试设计它们以使其适合(通过减少height
、 padding
、 margin
等)。 但是,Angular 在mat-form-field
和包含的元素之间添加了元素。 由于视图封装,我无法从组件的 Sass 中设置这些元素的样式。 因此,即使我对模板中立即出现的所有内容进行样式设置,生成的元素也会具有高度、边距和填充,从而迫使观察到的元素位于工具栏之外。
我不想为这些组件包含全局样式,因为我不希望其他mat-form-field
受到影响。
关闭视图封装本质上与使用全局样式相同。
::ng-deep
已弃用,所以我不能使用它。
我可以从头开始设置我自己的input
和select
的样式,但随后我失去了 Material 提供的预建样式。 有什么方法可以设置这些 Material 组件的样式以适合我的工具栏吗?
我遇到了类似的问题,我已经用 div 包装组件解决了它,然后用这个在全局样式表中设置它的样式
.filters {
mat-form-field {
div.mat-form-field-flex {
align-items: flex-end;
}
div.mat-form-field-prefix {
padding-right: 12px !important;
}
}
}
在您的情况下,您可以将类(或 id)添加到工具栏或用 div 包装表单字段,以便封装您想要的规则。
我在全局样式表中添加了以下规则以使 mat-form-field 适合:
[the selector for the mat-form-field I wanted to affect]
.mat-form-field-flex, .mat-form-field-label-wrapper
padding-top: 0
.mat-form-field-wrapper
padding-bottom: 0
.mat-form-field-underline
bottom: 0
.mat-form-field-infix
border-top: 0
您可以在@Component 装饰器中设置encapsulation: ViewEncapsulation.None,
。
这将使组件摆脱有关样式的限制。 请记住,如果您使用全局样式,则必须注意正确的样式,我建议使用 BEM 来命名 CSS 样式,而不是使用通用命名。
您可以将subscriptSizing="dynamic"
添加到 mat-form-field。 这不会为 mat-form-field 下面的下标保留间距。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.