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

Angular响应式表单TS7053错误:嵌套FormArray访问异常求助

解决Angular响应式表单嵌套FormArray的TS7053类型错误

错误原因

item.get('rows')返回的类型是AbstractControl,而controls是FormArray特有的属性,TypeScript类型检查不允许直接访问该属性,因此抛出TS7053错误。

解决方案

步骤1:在TS文件中添加获取嵌套FormArray的方法

在组件类中新增方法,明确将rows断言为FormArray,提供类型安全的访问方式:

public usersForm!: FormGroup;

constructor() { }

ngOnInit(): void {
  this.usersForm = new FormGroup({
    users: new FormArray([
      new FormGroup({
        key: new FormControl(),
        rows: new FormArray([
          new FormGroup({
            updatedBy: new FormControl(this.formatFormValue('')),
            updatedAt: new FormControl(this.formatFormValue('')),
            comment: new FormControl(this.formatFormValue('')),
          }),
        ]),
      }),
    ]),
  });
}

getFormControl(): FormArray {
  return this.usersForm.get('users') as FormArray;
}

// 新增方法:获取指定用户的rows FormArray
getUserRows(userIndex: number): FormArray {
  return (this.getFormControl().at(userIndex) as FormGroup).get('rows') as FormArray;
}

步骤2:修改模板文件的循环与表单绑定

修正模板中的3处问题:

  1. 将formGroupName="i"和formGroupName="j"改为属性绑定[formGroupName]="i"、[formGroupName]="j",确保使用循环变量作为表单索引
  2. 使用新增的getUserRows(i).controls替代item.get('rows')['controls'],解决类型错误
  3. 将包裹rows的<span>改为<div>,避免行内元素导致表单绑定异常

修改后的模板代码:

<form [formGroup]="usersForm">
  <div formArrayName="users">
    <table *ngFor="let item of getFormControl().controls; let i = index" [class.table_margin]="i>0">
      <div [formGroupName]="i">
        <tr>
          <th>{{item.get('key').value}}</th>
        </tr>
        <div formArrayName="rows">
          <tr *ngFor="let data of getUserRows(i).controls; let j = index" [formGroupName]="j">
            <td>
              <input type="text" formControlName="comment">
            </td>
          </tr>
        </div>
      </div>
    </table>
  </div>
</form>

替代方案(模板内直接断言)

如果不想新增方法,也可以在模板中直接进行类型断言,但这种方式不利于代码维护:

<tr *ngFor="let data of (item.get('rows') as FormArray).controls; let j = index" [formGroupName]="j">

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:40:24