你这样做是错误的。要么你必须FormArray
与你的父母创建一个对话FormGroup
,然后将FormGroup
s 推送给它。或者您必须conversations
使用addControl
.FormGroup
我建议使用第一种方法。因此,您可以按照以下方式进行操作:
import { Component } from '@angular/core';
import { FormBuilder, FormArray, Validators, FormGroup } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
itemsForm: FormGroup;
selectConversionsForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.itemsForm = this.fb.group({
name: [null, Validators.required],
description: [null, Validators.required],
conversions: this.fb.array([])
});
// Seed selectConversionRows form group with the seed data
// Generally this would come from the user selection. I'm assuming that you're already getting that.
const conversions = [
{ conversion_id: 1 },
{ conversion_id: 2 },
{ conversion_id: 3 }
];
// Seeding the Conversions
this.selectConversionsForm = this.fb.group({
selectConversionRows: this.fb.array(conversions.map(conv => this.generateConversionFormArray(conv.conversion_id)))
});
const selectedConversions = this.selectConversionRows.value;
selectedConversions.forEach(conversion => this.conversionsArray.push(this.generateConversionFormArray(conversion.conversion_id)));
// EXPECTED RESULT:
// name: 'sample name',
// description: 'sample desc',
// conversions: [{conversion_id: 1}, {conversion_id: 2}, {conversion_id: 3}]
console.log(this.itemsForm.value);
}
generateConversionFormArray(id) {
return this.fb.group({
conversion_id: this.fb.control(id)
});
}
get conversionsArray() {
return (<FormArray>this.itemsForm.get('conversions'));
}
get selectConversionRows() {
return (<FormArray>this.selectConversionsForm.get('selectConversionRows'));
}
}
这是您参考的工作示例 StackBlitz。
更新:
以下是您在代码中的操作方式:
import { Component } from '@angular/core';
import { FormBuilder, FormArray, Validators, FormGroup } from '@angular/forms';
@Component({...})
export class AppComponent {
itemsForm: FormGroup;
selectConversionsForm: FormGroup;
constructor(private fb: FormBuilder) {
this.itemsForm = this.fb.group({
name: [null, Validators.required],
description: [null, Validators.required]
});
this.selectConversionsForm = this.fb.group({
selectConversionRows: this.fb.array([])
});
}
ngOnInit() {
this.onCreateItem();
}
onCreateItem() {
const conversions = [];
(this.selectConversionsForm.get('selectConversionRows') as FormArray).getRawValue().forEach(item => {
conversions.push({
conversion_id: item['conversion_id'],
});
});
this.itemsForm.addControl('conversions', this.fb.array(conversions.map(conv => this.fb.group({
conversion_id: this.fb.control(conv.conversion_id)
}))));
console.log(this.itemsForm.value);
}
}
PS:请阅读代码中的注释以了解更多信息。