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

Angular中push函数报错,push前如何格式化FormGroup?

Angular中FormGroup存入数组报错:ERROR TypeError: control.setParent is not a function

错误原因分析

你碰到的这个错误,核心问题出在错误地给FormArray传入了非表单控件类型的值。从你的代码看,this.transactionControl.controls.involvedParties应该是一个FormArray(Angular专门用来管理表单控件数组的类),但你调用push('tparty',this.involvedParty)时,第一个参数是字符串'tparty',这并不是AbstractControl(FormGroup/FormControl/FormArray的父类)的实例,FormArray在尝试给这个字符串设置父控件时,自然会抛出control.setParent is not a function的错误。

修正后的代码

先确认involvedParties是FormArray类型,然后只把合法的FormGroup实例push进去就行:

saveInvolvedParty(){
  if( this.From_type === '') {
    this.toaster.warning("Please select InvolvedParty Type");
  } else {
    // 明确指定类型为FormArray,避免类型歧义
    const involvedPartiesArray = this.transactionControl.get('involvedParties') as FormArray;
    // 只push你的FormGroup实例,不需要额外的字符串参数
    involvedPartiesArray.push(this.involvedParty);
    
    console.log('control...', involvedPartiesArray);
    console.log('control...', this.transactionControl);
    this.sendInvolvedPartyToList.emit(this.tparty);
  }
}

关于push前如何“格式化”FormGroup的问题

其实不需要额外的“格式化”操作,关键是要保证你要push的this.involvedParty是一个合法的FormGroup实例,这里给你两种常见的创建方式:

  • 直接创建新的FormGroup(推荐用FormBuilder简化代码):

    // 假设你已经在构造函数里注入了FormBuilder:private fb: FormBuilder
    this.involvedParty = this.fb.group({
      partyType: ['', Validators.required], // 对应你的表单字段,示例添加了必填校验
      partyName: ['', Validators.required],
      // 其他需要的表单控件
    });
    
  • 从后端数据转换为FormGroup:
    如果你的involvedParty是从后端接口获取的普通对象,需要把它映射成FormGroup:

    // 假设backendData是后端返回的参与方数据
    this.involvedParty = this.fb.group({
      partyType: [backendData.partyType, Validators.required],
      partyName: [backendData.partyName, Validators.required],
    });
    

另外要注意:如果是需要复用同一个FormGroup实例(比如用户多次添加相同结构的参与方),一定要创建实例的副本,否则会出现同一个控件被多个父容器引用的问题,比如:

const newPartyCopy = this.fb.group({
  ...this.involvedParty.value // 深拷贝原FormGroup的值创建新实例
});
involvedPartiesArray.push(newPartyCopy);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:09:34