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

Angular动态表格绑定FormArray获取所有行值为空如何解决

问题根源

你当前代码的核心问题是FormArray和表格的数据源没有建立双向绑定,表单配置、绑定逻辑都存在错误:

  1. 初始化时只给genderDataSource赋值,没有把接口返回的性别值推到FormArray中,patchValue无法为空的FormArray批量赋值
  2. 新增/删除行时仅修改了表格数据源genderDataSource,没有同步修改FormArray
  3. HTML的input没有绑定对应索引的FormControl,仅声明formArrayName无法和每行的输入框建立关联
  4. input同时使用[value]和表单绑定会产生冲突,表单绑定会自动处理值同步,不需要额外加[value]属性

修改后的TS代码

import { FormArray, FormControl, FormGroup } from '@angular/forms'; // 确保引入需要的表单类

export class AnredeKategorieComponent implements OnInit {

  public displayedColumns = ['edit', 'delete', 'bezeichnung'];
  public genderDataSource: any[];
  public anreden = [] as any;
  genderForm = new FormGroup({
    anrede: new FormArray([]),
  })
  // 便捷获取FormArray的getter,简化后续调用
  get anredeFormArray(): FormArray {
    return this.genderForm.get('anrede') as FormArray;
  }
  constructor(
    public aService: AnredeVorschlägeService,
  ) { }
  @ViewChild('genderTable') table: MatTable<any>;
  ngOnInit(): void {
    //Alle Anreden
    this.aService.getAnrede()
    .subscribe(
      data => { 
        this.anreden = data;
        console.log(this.anreden);
        this.genderDataSource = data;
        this.getStandardValues();
    });
  }
  addRow(){
    let newCase = { bezeichnung: ''};
    this.genderDataSource.push(newCase);
    // 新增行同步给FormArray添加对应FormControl
    this.anredeFormArray.push(new FormControl(newCase.bezeichnung));
    this.table.renderRows();
  }
  saveRow(){
    console.log(this.genderForm.getRawValue());
  }
  getStandardValues(){
    // 清空原有FormArray,避免重复添加控件
    this.anredeFormArray.clear();
    // 遍历接口返回的数据,逐个生成FormControl推入FormArray
    this.anreden.forEach(item => {
      this.anredeFormArray.push(new FormControl(item.bezeichnung));
    })
  }
  delRow(i:any){
    this.genderDataSource.splice(i, 1);
    // 删除行同步移除FormArray对应索引的控件
    this.anredeFormArray.removeAt(i);
    this.table.renderRows();
    console.log(i);
  }
}

修改后的HTML核心部分(仅调整bezeichnung列代码,其余代码保持不变)

<ng-container matColumnDef="bezeichnung">
  <th mat-header-cell *matHeaderCellDef> Bezeichnung </th>
  <td mat-cell *matCellDef="let anreden; let i = index" formArrayName="anrede"> 
    <ng-container>
      <mat-form-field appearance="standard">
        <input matInput type="text" [formControlName]="i"> 
      </mat-form-field>
    </ng-container>       
  </td>
</ng-container>

修改完成后点击保存按钮,即可通过getRawValue()正常获取所有行的输入值,包括接口加载的默认值和新增行的输入值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:45:02