窗体数组在推送新的窗体组后清除值(但不是控件)



我正在尝试将FormGroup(myGroup)推送到FormArray(myArray)中,该FormArray内部已经有一堆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 中现有的 FormGroups 之一,它的行为就像正常一样,一切正常。
  2. 最初,我使用与后来推送myGroup(createGroup())相同的方法动态填充myArray,该方法也按预期工作。
  3. 窗体是嵌套的。我当前的结构是:myForm -> 包含 myParentArray -> 包含 myParentGroup -> 包含 myArray。
  4. 我最初使用返回例如的服务在父组件中创建整个表单。像myGroup这样的FormGroup。然后我通过 @Input() 将 FormGroups 和 FormArray 传递给嵌套组件。但在我看来,这应该不会有什么不同。

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

也许有什么方法可以强制 FormArray 根据控件更新其值?

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

最新更新