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

Angular中FormArray出现Cannot find control with path报错如何解决?

问题解决方法

错误根因

  • 模板中遍历FormArray的*ngFor被注释,导致索引变量i未定义,[formGroupName]="i"无法绑定到正确的数组索引,表单路径缺失层级
  • 初始化时answerDetails是长度为0的空FormArray,不存在对应的子FormGroup控件
  • 模板中引用的FormArray变量名AnswerDetails大小写和TS文件中定义的answerDetails不一致,无法正确读取控件列表

修复步骤

第一步:修改TS文件,添加FormArray getter并初始化默认子控件

// 类中新增getter,方便模板访问FormArray
get answerDetails(): FormArray {
  return this.vgaReportForm.get('answerDetails') as FormArray;
}

ngOnInit(): void {
  this.getVgAuditDetails();
  this.vgaReportForm = this.formBuilder.group({
    section_id: [this.sectionId],
    userId: [this.userObj.id],
    QuestionId: [this.questionId],
    answerDetails: this.formBuilder.array([]),
    vgaAuditNumber: [this.vgAudit.vga_audit_number],
    clientId: [this.clientId]
  });
  // 初始化后添加1条默认的子表单控件
  this.addAnswerDetails();
}

// 原有newAnswerDetails、addAnswerDetails、onSubmit方法保留即可

第二步:修改HTML模板,取消注释并修正变量

<form action="" [formGroup]="vgaReportForm" (ngSubmit)="onSubmit()">
  <div formArrayName="answerDetails">
    <!-- 取消原有注释,修正FormArray变量名大小写,将formGroupName移到循环节点上 -->
    <div *ngFor="let vg of answerDetails.controls; let i=index" [formGroupName]="i">
      <table class="table table-striped table-bordered table-hover dataTable">
        <thead>
          <tr class="thead">
            <th style="width: 25%">Zone of the Sphere</th>
            <th style="width: 25%">Strategic Intent</th>
          </tr>
          <tr>
            <td>Core</td>
            <td> <input type="text" class="form-control" formControlName="core"> </td>
          </tr>
          <tr>
            <td>Vital Interests</td>
            <td> <input type="text" class="form-control" formControlName="vitalInterests"> </td>
          </tr>
          <tr>
            <td>Buffer Zones</td>
            <td> <input type="text" class="form-control" formControlName="bufferZones"> </td>
          </tr>
          <tr>
            <td>Pivotal Zones</td>
            <td> <input type="text" class="form-control" formControlName="pivotalZones"> </td>
          </tr>
          <tr>
            <td>Forward Positions</td>
            <td> <input type="text" class="form-control" formControlName="forwardPositions"> </td>
          </tr>
          <tr>
            <td>Power Vacuums</td>
            <td> <input type="text" class="form-control" formControlName="powerVaccums"> </td>
          </tr>
        </thead>
      </table>
    </div>
  </div>
  <!-- 可选:添加动态新增条目按钮、提交按钮 -->
  <button type="button" (click)="addAnswerDetails()">新增条目</button>
  <button type="submit">提交表单</button>
</form>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 04:57:04