You need to enable JavaScript to run this app. Angular响应式表单如何为嵌套对象数组声明FormArray支持行列增删与回填
优惠活动
大模型
产品
解决方案
定价
更多

Angular响应式表单如何为嵌套对象数组声明FormArray支持行列增删与回填

解决方案

核心思路

你的场景需要嵌套FormArray结构:外层matrix是行级FormArray,每个行元素是FormGroup,内部包含列级的items FormArray,对应每列的配置,结构完全对齐你接口返回和需要的输出格式。

注意:你原定义的MatrixDTO里的name字段在需求和接口返回中都没有用到,如果确实不需要可以直接从DTO中删除,避免冗余。


1. 定义基础控件生成方法

先封装两个公共方法用来生成行和列的表单控件,后续增删操作和数据回填都可以复用:

// 生成单个列的FormGroup
colGroup(col: cols = {label: '', customCol: false}): FormGroup {
  return this.fb.group({
    label: [col.label],
    customCol: [col.customCol]
  })
}

// 生成单个行的FormGroup
rowGroup(row: MatrixDTO = {label: '', customRow: false, items: []}): FormGroup {
  // 把行的items转换成列FormArray
  const colsArr = this.fb.array(
    row.items.map(item => this.colGroup(item))
  )
  return this.fb.group({
    label: [row.label],
    customRow: [row.customRow],
    items: colsArr
  })
}

// 封装获取matrix FormArray的快捷方法
get matrixArr(): FormArray {
  return this.matrixForm.get('matrix') as FormArray
}

// 获取指定行下的items FormArray的快捷方法
getItemsArr(rowIndex: number): FormArray {
  return this.matrixArr.at(rowIndex).get('items') as FormArray
}

2. 表单初始化调整

初始化逻辑保持不变,默认是空的FormArray即可,注意修正原代码的拼写错误initilazie为initialize:

initializeForm(): void {
  this.matrixForm = this.fb.group({      
    matrix: this.fb.array([], [Validators.required]),  
  });
}

3. 编辑页回填数据修正

你之前的patchValue写法存在两个问题:

  1. patchValue只能传入普通值对象,不能直接传入FormGroup实例
  2. 字段大小写和接口返回不一致(比如你写的Brand、Market是大写开头,接口返回是小写的brand、market)

正确的回填写法如下:

setFormValues(data: any) {
  console.log(data);
  // 先给其他基础控件赋值
  this.specForm.patchValue({
    name: data.name,
    brand: data.brand,
    market : data.market,
    productName : '',
    isArchived : data.isArchived,
    isCustom : data.isCustom,
    // 注意不要在这里给FormArray赋值,要单独操作
  });
  // 清空现有matrix的旧控件
  this.matrixArr.clear();
  // 遍历接口返回的matrix数据,逐个生成行控件加入FormArray
  data.matrix.forEach(row => {
    this.matrixArr.push(this.rowGroup(row))
  })
}

4. 新增/删除行列操作实现

新增行

addNewRow(): void {
  // 新增行默认customRow为true,列数和现有行保持一致,无数据时默认3列
  const colCount = this.matrixArr.length ? this.getItemsArr(0).length : 3;
  const newRow = {
    label: null,
    customRow: true,
    items: new Array(colCount).fill({label: '', customCol: true})
  }
  this.matrixArr.push(this.rowGroup(newRow))
}

新增列(给所有行都加一列)

addNewCol(): void {
  // 遍历每一行,给每行的items都加一个新的列控件
  this.matrixArr.controls.forEach(rowGroup => {
    const itemsArr = rowGroup.get('items') as FormArray;
    itemsArr.push(this.colGroup({label: '', customCol: true}))
  })
}

删除指定行

deleteRow(rowIndex: number): void {
  this.matrixArr.removeAt(rowIndex)
}

删除指定列(删除所有行对应下标的列)

deleteCol(colIndex: number): void {
  this.matrixArr.controls.forEach(rowGroup => {
    const itemsArr = rowGroup.get('items') as FormArray;
    itemsArr.removeAt(colIndex)
  })
}

5. 模板渲染逻辑

渲染的时候判断customRow和customCol的值,决定显示标签还是输入框:

<form [formGroup]="matrixForm">
  <div formArrayName="matrix">
    <div *ngFor="let rowGroup of matrixArr.controls; let rowIndex = index" [formGroupName]="rowIndex">
      <!-- 行标签判断 -->
      <ng-container *ngIf="rowGroup.value.customRow; else rowLabel">
        <input type="text" formControlName="label" placeholder="请输入行名">
      </ng-container>
      <ng-template #rowLabel>
        <span>{{rowGroup.value.label}}</span>
      </ng-template>

      <!-- 列渲染 -->
      <div formArrayName="items">
        <div *ngFor="let colGroup of getItemsArr(rowIndex).controls; let colIndex = index" [formGroupName]="colIndex">
          <ng-container *ngIf="colGroup.value.customCol; else colLabel">
            <input type="text" formControlName="label" placeholder="请输入值">
          </ng-container>
          <ng-template #colLabel>
            <span>{{colGroup.value.label}}</span>
          </ng-template>
        </div>
      </div>
    </div>
  </div>
</form>

6. 表单保存

直接取表单值即可,结构完全符合你需要的格式:

saveForm() {
  const formValue = this.matrixForm.value;
  console.log('提交数据', formValue.matrix)
  // 直接调用接口提交即可
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 08:27:10