我正在寻找实现表单编辑器的最佳方法,该表单编辑器可以使用数据库中的值进行初始化。因此,现在我已经构建了一个反应式表单,该表单在用户想要使用给定结构创建新表单时定义一个表单。 表单是这样构建的:
调查(FormGroup) -名称(FormControl) -部分(FormArray)
部分(FormGroup) -标题(FormControl) -问题(FormArray)
问题(FormGroup) -标题(formControl) -类型(formControl) -QuestionGroup(FormGroup)-如果出现multipleChoice Question
反应式表单生成器的TS代码
ngOnInit() {
this.initSurveyForm();
}
// Initialize new Survey
private initSurveyForm() {
this.surveyForm = this.fb.group({
surveyTitle: ['', Validators.required],
surveyDescription: ['', Validators.required],
surveyCategory: this.fb.array([
this.initSurveyCategory()
])
});
}
// Initialize category
initSurveyCategory() {
return this.fb.group({
categoryTitle: ['', Validators.required],
categoryDescription: ['', Validators.required],
categoryQuestion: this.fb.array([
this.initCategoryQuestion()
])
});
}
// Initialize question
initCategoryQuestion() {
return this.fb.group({
questionTitle: ['', Validators.required],
questionType: ['', Validators.required],
questionGroup: this.fb.group({
})
})
}
//Add new Category to surveyForm
onAddSurveyCategory() {
this.surveyCategories.push(this.initSurveyCategory());
}
//Remove category from a survey
onRemoveCategory(index) {
(<FormArray>this.surveyForm.get('surveyCategory')).removeAt(index);
console.log(this.surveyForm);
}
//Add new question to a category
onAddCategoryQuestion(index) {
const control = (<FormArray>this.surveyForm.controls.surveyCategory['controls'][index].controls.categoryQuestion);
control.push(this.initCategoryQuestion());
}
现在,当用户创建此类表单并将值保存到数据库中时,我希望能够返回并编辑此类表单。因此,如果用户使用2个部分(FormArray),当他从表中选择表单时,该表单又显示为2个部分。
我被困在这一点上。到目前为止,是否可以用我的方法来实现?