您正在混合演示视图和表单的值。我认为最好将概念分开。我们可以使用 formObj 来创建表示,并使用 callbackForm 来创建值。查看代码中的cmets
//app.main.html
<form [formGroup]="callbackForm" (submit)=submit(callbackForm)>
<div>
<div formArrayName="componentDetails">
<div *ngFor="let question of callbackForm.controls.componentDetails.controls; let i = index;" [formGroupName]="i">
<div class="row">
<div class="col-md-12 panel-group panel-group--compressed">
<div class="panel panel--default">
<fieldset>
<!--see that we create the "view of the form using formObj.componentDetails--!>
<div class="row" *ngIf="formObj.componentDetails[i].type === 'radio'">
<div class="col-md-12">
<p>{{ formObj.componentDetails[i].label }}</p>
<p>{{ formObj.componentDetails[i].cpv }}</p>
<!-- we iterate throught "formObj.componentDetails[i].component -->
<!-- again, we are using formObj to the "view" -->
<div *ngFor="let answer of formObj.componentDetails[i].component; let j = index">
<label class="radio radio--alt radio--stacked">
<span class="radio__input"></span>
<span class="radio__label">{{ answer.value }}</span>
</label>
<!--We have a input with name=formObj.componentDetails[i].cpv -->
<!--it's necesary enclose between {{ }} the name -->
<input type="radio" formControlName="{{formObj.componentDetails[i].cpv}}" [value]="answer.selectedValue">
</div>
</div>
</div>
</fieldset>
</div>
</div>
</div>
</div>
</div>
</div>
<button type="submit">send</submit>
</form>
<pre>{{callbackForm.value | json}}</pre>
//app-main.component
@Component({
selector: 'app-app-main',
templateUrl: './app-main.component.html'
})
export class AppMainComponent {
constructor(private _formBuild: FormBuilder) {}
ngOnInit() {
this.loadObservableForm();
}
public callbackForm: FormGroup;
formObj = {
"componentDetails": [{
"component": [{
"value": "Choice 1",
"selectedValue": true
}, {
"value": "Choice 2",
"selectedValue": false
}],
"cpv": "name1", //<--we use this to create the name of the fileld
"label": "Description of Problem",
"type": "radio",
"mandatory": true
}]
};
loadObservableForm() {
this.callbackForm = this._formBuild.group({
componentDetails: this._formBuild.array([])
});
this.addComponentDetails();
}
addComponentDetails() {
const control = <FormArray>this.callbackForm.controls.componentDetails;
this.formObj.componentDetails.forEach(x => {
control.push(this.addControl(x));
});
}
addControl(x) {
//we create a group control with a control with a name "x.cpv"
const group = this._formBuild.group({});
group.addControl(x.cpv,new FormControl());
return group;
}
我们有一个 callbackForm 方式为 "componentDetails": [{"name1": false},{"name2":value2}...]。所以,在提交中我们可以做一些类似的事情
submit(form)
{
if (form.valid)
{
let response:any={}
for (let control of form.value.componentDetails)
response={...response,...control}
console.log(response);
}
}