1

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[]
                  }]
}

1 Answer 1

3

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()
              })])
        });
}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.