首页 > 解决方案 > FormArray 在推送新的 FormGroup 后清除值(但不是控件)

问题描述

我正在尝试将 FormGroup (myGroup) 推送到 FormArray (myArray) 中,其中已经有一堆 FormGroups。推送 myGroup 后,我记录 myArray.value,然后它只包含 myGroups 值。但是: myArray.controls 仍然包含所有其他 formGroups。

任何人都经历过这种行为或有任何想法,为什么会发生这种情况?已经在网上搜索过,但找不到任何相关内容。

// at this point the array contains n values and n controls
console.log(this.myArray.value)  

// then I push the new group (result comes from input data of the user)
const myGroup = this.myService.createGroup(result);
(<FormArray>this.myArray).push(<FormGroup>myGroup);

// at this point the array contains only one value, but still n controls
console.log(this.myArray.value);

我的服务:

createGroup(result: Result) {
  return this.fb.group({
    id: this.fb.control(result.id),
    name: this.fb.control(result.name)
  });
}

有几件事可能与此相关:

  1. 如果我用 patchValue 更新 myArray 中现有的 FormGroup 之一,它的行为就像正常一样,一切正常。
  2. 最初,我使用与稍后推送 myGroup (createGroup()) 相同的方法动态填充 myArray,该方法也可以按预期工作。
  3. 表单是嵌套的。我当前的结构是:myForm -> 包含 myParentArray -> 包含 myParentGroup -> 包含 myArray。
  4. 我最初使用服务在父组件中创建整个表单,该服务返回例如。像 myGroup 这样的 FormGroups。然后我通过 @Input() 将 FormGroups 和 FormArrays 传递给嵌套组件。但这不应该在我看来有所作为。

我已经尝试过使用 .updateValueAndValidity() 更新值,但这不起作用。

也许有任何方法可以强制 FormArrays 根据控件更新它们的值?

标签: angularformsreactive-formsformarray

解决方案


正如@Eliseo 指出的那样,我的解决方案只是通过 .getRawValue() 获取值。但主要的错误是,在代码的其他部分,formArray 中的 formControls 被禁用,这导致了最初的问题。


推荐阅读