angular - 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)
});
}
有几件事可能与此相关:
- 如果我用 patchValue 更新 myArray 中现有的 FormGroup 之一,它的行为就像正常一样,一切正常。
- 最初,我使用与稍后推送 myGroup (createGroup()) 相同的方法动态填充 myArray,该方法也可以按预期工作。
- 表单是嵌套的。我当前的结构是:myForm -> 包含 myParentArray -> 包含 myParentGroup -> 包含 myArray。
- 我最初使用服务在父组件中创建整个表单,该服务返回例如。像 myGroup 这样的 FormGroups。然后我通过 @Input() 将 FormGroups 和 FormArrays 传递给嵌套组件。但这不应该在我看来有所作为。
我已经尝试过使用 .updateValueAndValidity() 更新值,但这不起作用。
也许有任何方法可以强制 FormArrays 根据控件更新它们的值?
解决方案
正如@Eliseo 指出的那样,我的解决方案只是通过 .getRawValue() 获取值。但主要的错误是,在代码的其他部分,formArray 中的 formControls 被禁用,这导致了最初的问题。
推荐阅读
- google-apps-script - 有没有办法在没有标准 GCP 项目的情况下查看 Stackdriver 错误报告?
- php - 我如何在 Laravel 中更改数据库名称?我已经更改了 config/database.php 和 .env 中的数据库
- javascript - 如何“返回”分页项目
- django - Django通过相关管理器列中的外键过滤表
- php - 将 PHP 5 升级到 PHP 7 后找不到数据库变量
- elixir - 有什么方法可以在不使用 ParallelCompiler 方法的情况下读取文件并获取 Elixir 中该文件中定义的模块列表?
- .net - Google Chrome 无法识别 .NET MVC 中大于 3 位数的数字
- java - Java - srcset 属性 - 拆分 - 用逗号处理url和用逗号分隔的属性值
- voicexml - 能够将语音菜单选项与使用 VoiceXML 和 Plum Voice 录制音频合并
- angular - 如何测试包含 SwitchMap 的嵌套服务调用