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

Angular表单报错:Cannot find control with name: '0' 求助解决

问题排查:Error: Cannot find control with name: '0'

错误原因

模板未正确关联FormArray与子FormGroup的上下文:遍历grantsFormArray.controls时,未先指定formArrayName="grants",直接使用[formGroupName]="i"会导致Angular无法识别子FormGroup所属的FormArray,因此抛出找不到名称为'0'的控件的错误。

修复步骤

在遍历FormArray控件的外层容器上添加formArrayName="grants",确保[formGroupName]="i"处于FormArray的作用域内。

修改后的HTML代码

<form [formGroup]="permissionsForm">
  <div class="p-4 border dark:border-gray-700 rounded w-full shadow-sm">
    <!-- ... 其他代码保持不变 ... -->
    <h3 class="font-medium text-secondary dark:text-white text-lg mb-4 flex justify-between flex-wrap">
      {{'institutionGrants' | translate}}
      <button class="btn btn-primary dark:btn-accent btn-sm text-white" (click)="addNewPermissionsSet()">
        {{'addAdditionalInstitutionGrants' | translate}}
      </button>
    </h3>
    <h4 class="flex justify-between mb-3 text-base">
      <span>{{'institution(s)' | translate}}:</span>
      <span *ngFor="let institute of userPermissions">
        <a class="link text-primary dark:text-accent font-medium">Intelegencia Okta</a>
      </span>
    </h4>
    <!-- 新增formArrayName="grants",关联表单中的FormArray -->
    <div formArrayName="grants" *ngFor="let grantControl of grantsFormArray.controls; let i = index">
      <ng-container [formGroupName]="i">
        <div *ngFor="let action of getControls(grantControl) | keyvalue">
          {{action.key}}
          <label class="cursor-pointer label mb-1 rounded px-3 border dark:border-gray-700">
            <span>{{ formControlLabelMapping[action.key] }}</span>

            <span *ngIf="!isEditMode" [ngClass]="{'text-green-500': action.value.value, 'text-neutral': !action.value.value}">
              <em class="ph-bold" [ngClass]="{'ph-check-circle': action.value.value, 'ph-x': !action.value.value}"></em>
              {{ action.value.value ? 'Yes' : 'No' }}
            </span>
            
            <input *ngIf="isEditMode" type="checkbox" class="toggle toggle-primary toggle-sm" [formControlName]="action.key"/>
          </label>
        </div>
      </ng-container>
    </div>
    <!-- ... 其他代码保持不变 ... -->
  </div>
</form>

额外验证

组件中的表单初始化逻辑(initializeForm方法)是正确的:遍历userPermissions为每个Grant创建包含所有action控件的FormGroup,并添加到FormArray中。修复模板的表单结构关联后,错误即可解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 23:29:52