我正在尝试为 angular 2 react 形式 formArray 对象设置初始值。
即使用于设置表单值的 json 对象包含具有多个条目的数组值,但仅显示第一个条目,“form.value”也仅显示第一个条目。
我使用的语法是 (<FormGroup>this.myForm).patchValue(value, { onlySelf: true });
在表单上设置初始值。
这里有一个 plunker 演示了这个问题:https://plnkr.co/edit/j1S80CmPBF1iHI5ViEia?p=preview
我使用了 https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 中的示例创建 plunker。
知道我做错了什么吗?
最佳答案
您将 addresses
设置为一组表单,并且在 initAddress()
方法中您只返回一个元素。
如果您向 addresses
数组添加第二次调用,您将获得第二个地址。
this.myForm = this._fb.group({
name: ['', [Validators.required, Validators.minLength(5)]],
addresses: this._fb.array([
this.initAddress(),
this.initAddress()
])
});
这听起来有点愚蠢,但它会返回位于数组中的元素,如果你超过数组中元素的数量,你将得到一个空元素。
希望对您有所帮助。
关于forms - 设置初始值Angular 2 reactive formarray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40875283/