答案 0 :(得分:1)
检查一下。我正在使用FormGroupArray创建动态的问题/选项列表。
// Component
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormArray } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
public view: any;
surveyForm: FormGroup;
surveyQuestions: FormArray;
surveyOptions: any[] = [];
formData: string;
constructor(private formbuilder: FormBuilder) {
}
ngOnInit() {
this.surveyForm = this.formbuilder.group({
survey: this.formbuilder.array([this.createSurveyQuestion()])
});
}
createSurveyQuestion(): FormGroup {
return this.formbuilder.group({
question: [''],
options: this.formbuilder.array([this.createOption()])
});
}
createOption(): FormGroup {
return this.formbuilder.group({
option: ['']
});
}
addQuestion(): void {
this.surveyQuestions = this.surveyForm.get('survey') as FormArray;
this.surveyQuestions.push(this.createSurveyQuestion());
}
addOption(indx: number): void {
let questCtrl = <FormArray>this.surveyForm.get('survey');
let m = questCtrl.controls[indx];
let opts = m.get('options') as FormArray;
opts.push(this.createOption());
}
get getSurveyControls() {
return <FormArray>this.surveyForm.get('survey');
}
getQuestionOptionControls(questIndex: number){
let questCtrl = <FormArray>this.surveyForm.get('survey');
let m = questCtrl.controls[questIndex];
let opts = <FormArray>m.get('options');
return opts;
}
convertFormData() {
this.formData = JSON.stringify(this.surveyForm.value);
}
}
模板-
// Template
<form [formGroup]="surveyForm">
<button (click)="addQuestion()">Add Question</button>
<div formArrayName="survey" *ngFor="let quest of getSurveyControls.controls; index as i;" [attr.data-index]="i">
<div [formGroupName]="i">
<input formControlName="question" placeholder="Question"/>
<button (click)="addOption(i)">Add Option</button>
<div formArrayName="options" *ngFor="let opt of getQuestionOptionControls(i).controls; index as oidx;"[attr.data-index]="oidx">
<div [formGroupName]="oidx">
<input formControlName="option" placeholder="option"/>
</div>
</div>
</div>
</div>
</form>
<pre> {{surveyForm.value | json }}</pre>