Reputation: 81
Im trying to create an array of FormGroup inside a Formgroup and I cant seem to make it work
ngOnInit(): void {
this.surveyForm = new FormGroup({
'surveyTitle': new FormControl(null, Validators.required),
'surveyDescription': new FormControl(null),
'questionsDetail': new FormGroup(
{
'questionType' : new FormControl('mcq'),
'question': new FormControl(null),
'choices': new FormArray([])
}),
});
Im hoping to make the questionsDetail an array so i can have multiple questionsDetail in 1 survey.
My Question is How do i initialize my questionsDetails to be an array of FromGroup so that everytime i press a next button, it will push the current values to my questionDetails?
So that everytime I submit the form, its in this model
surveyForm = {
surveyTitle: string,
surveyDescription: string,
questionsDetails: [{
questionType: string
question: string
choices: string[]
}]
}
Upvotes: 1
Views: 1081
Reputation: 95
You can try using FormBuilder for this. Here's one example of how you'd create an array with FormBuilder:
formExample: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit(): void {
this.formExample = this.formBuilder.group({
item1: new FormControl(),
item2: new FormControl(),
itemArray: this.formBuilder.array([
this.formBuilder.group({
arrayItem1: new FormControl(),
arrayItem2: new FormControl()
})])
});
}
Upvotes: 3