You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular响应式表单中添加mat-button-toggle组后其他控件消失如何解决?

问题修复方案

根因说明

你遇到的表单字段消失问题由两处错误导致:

  1. 模板中mat-button-toggle-group绑定的formControlName属性多了一个多余的末尾单引号,属于模板语法错误,会触发Angular模板解析异常,导致整个表单渲染失败
  2. mat-button-toggle-group不属于Angular Material mat-form-field支持的内置输入控件,不能嵌套在mat-form-field标签内使用

修复步骤

1. 修改模板代码

移除多余的单引号,同时把mat-button-toggle-group从mat-form-field中移出,修复后的对应代码如下:

<!-- 原有三个mat-form-field字段代码保持不变 -->
<mat-form-field class="form-field" appearance="outline">
  <mat-label>Author</mat-label>
  <input matInput placeHolder="Binding Author" formControlName="authorName" required>
  <mat-error *ngIf="bindingAuthorForm.controls['authorName'].hasError('required')">
    <span>Author Name is required. </span>
  </mat-error>
</mat-form-field>

<!-- 修复后的toggle组件代码 -->
<div class="form-field">
  <label>Binding Type</label>
  <mat-button-toggle-group formControlName="bindingType">
    <mat-button-toggle value="definitions">Definitions</mat-button-toggle>
    <mat-button-toggle value="entitlements">Entitlements</mat-button-toggle>
  </mat-button-toggle-group>
</div>

2. 可选样式调整

可以给外层的.form-field类添加统一的上下边距,保证toggle组件和上方输入框的布局间距一致。

3. 验证修复

修改完成后重新编译项目,原有表单字段即可正常显示,toggle组件也可以正常绑定表单值。

内容的提问来源于stack exchange,提问作者GGizmos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 09:54:03