如何实现Angular Material mat-form-field内两个输入框同行展示
解决方案
你可以通过外层套flex横向布局容器,配合调整Angular Material表单域的内置样式实现所有元素同行展示,以下是修改后的代码:
修改后的HTML代码
<mat-form-field appearance="fill"> <!-- 新增flex横向布局容器包裹所有输入和图标元素 --> <div fxLayout="row" fxLayoutAlign="start center" fxFill fxGap="8px"> <div fxFlex="45%"> <input matInput formControlName="field1" required type="number" min="0" /> <span matSuffix>h</span> </div> <div fxFlex="45%"> <input matInput formControlName="field2" required type="number" min="0" /> <span matSuffix>min</span> </div> <mat-icon matSuffix>access_time</mat-icon> <mat-error style="display: inline-block; margin: 0 0 0 8px;">Required</mat-error> </div> </mat-form-field>
配套全局/组件样式调整
/* 覆盖mat-form-field默认的内边距与布局限制 */ mat-form-field { width: 100%; ::ng-deep .mat-form-field-wrapper { padding-bottom: 0 !important; } ::ng-deep .mat-form-field-flex { align-items: center; } /* 调整输入框宽度避免挤压换行 */ input[matInput] { min-width: 60px; width: 100%; } }
注意事项
- 新增的
fxLayout="row"容器会强制所有子元素横向排列,fxGap用来控制元素间距,你可以根据需求调整两个输入框的fxFlex占比 - 用
::ng-deep覆盖Material内置样式是为了取消默认的上下内边距,让所有元素垂直居中对齐 - 如果不需要错误提示和输入同行,只需把
mat-error放到flex容器外即可,不会影响输入框和图标同行的效果
内容的提问来源于stack exchange,提问作者GPiter
相关产品推荐
相关产品推荐

