首页 > 解决方案 > 将角材料的文本区域设置为组件的 50%

问题描述

我正在 Angular 6 中创建一个应用程序(我计划将其迁移到 ng7),并且其中一个组件需要添加 2 个元素,ng material 的 textarea 和我的自定义组件。每个应占可用高度的 50%。我对 textarea 有疑问,因为生成的 mat-form-field-wrapper 只占用它需要的空间,而且我无法在该元素中实现我的目标(我不想使用任何 ::ng-deep 解决方案作为不推荐)

这是我到目前为止所做的(当然是一个示例):

<form [formGroup]="myGroup" fxLayout="column" fxLayoutAlign="center stretch" fxFlex="1 1 100%">
  <mat-form-field fxFlex="1 1 100%" fxLayout="column" fxLayoutAlign="start stretch">
    <textarea matInput formControlName="myControl" fxFlex="1 1 100%"></textarea>
  </mat-form-field>
</form>

<my-custom-component *ngIf="somevariable" [variable]="somevariable"></my-custom-component>

标签: cssangularangular-material2

解决方案


您将需要覆盖全局样式表中的样式,以替代使用深度。由于表单字段元素的布局方式和可变填充等,我不相信你可以在所有条件下完美地完成这项工作,但这是一个起点:

<form [formGroup]="myGroup" style="display: flex; flex-direction: column; height: 50%;">
  <mat-form-field class="stretch-height">
    <textarea matInput formControlName="myControl"></textarea>
  </mat-form-field>
</form>

<my-custom-component style="height: 50%" *ngIf="somevariable" [variable]="somevariable"></my-custom-component>

全局 CSS:

.mat-form-field.stretch-height,
.mat-form-field.stretch-height .mat-form-field-flex,
.mat-form-field.stretch-height textarea {
  height: 100%;
}
.mat-form-field.stretch-height .mat-form-field-wrapper {
  height: calc(100% - 1.34375em);
}
.mat-form-field.stretch-height .mat-form-field-infix {
  height: calc(100% - 1.34375em - 2px);
}

父容器的高度必须为 100% 或您希望的高度,这一点至关重要。

这是StackBlitz上的演示。


推荐阅读