Accessing the data withing a FormBuilder from the html

702 Views Asked by At

so I initialized a FormBuilder in the onInit Lifecyle:

surveyForm: FormGroup;
ngOnInit(): void {
     this.surveyForm = this.formBuilder.group({
       'surveyTitle': new FormControl(null),
       'surveyDescription': new FormControl(null),
       'questionsDetail': this.formBuilder.array([
         this.formBuilder.group({
           'questionType': new FormControl('mcq'),
           'question': new FormControl(null),
           'choices': this.formBuilder.array([])
         })
       ])
     });
    };

I cant figure out how to access the controls of my FormArray

<form [formGroup]="surveyForm">
  <input formControlName = "surveyTitle">
  <textarea formControlName = "surveyQuestion"></textArea><div formArrayName='questionsDetail'>
    <div [FormArrayName]="questionsDetail">
      <div *ngFor="let questionDetail of surveyForm.get('questionsDetail').controls; let i=index">
        <div [FormGroup]="i">
          ...
          <div [FormArrayName]="choices">
            <div *ngFor="let choice of surveyForm.get('questionsDetail').controls.get('choices').controls; let in=index">
              <div [FormGroup]="in">
                ...
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </form>

so can anyone show me the syntax of getting the data inside FormGroup which is nested inside a FormArray. I cant seem to get the correct syntax for ngFor in accessing the formBuilder.

If you can help me, that would be great.

Thanks in advance.

1

There are 1 best solutions below

4
On BEST ANSWER

Try below

<form [formGroup]="surveyForm">
  <input formControlName = "surveyTitle">
  <textarea formControlName = "surveyQuestion"></textArea><div formArrayName='questionsDetail'>
    <div formArrayName="questionsDetail">
      <div *ngFor="let questionDetail of surveyForm.get('questionsDetail')['controls']; let i=index">
        <div [FormGroup]="i">
          ...
          <div formArrayName="choices">
            <div *ngFor="let choice of surveyForm.get('questionsDetail')['controls'][i].get('choices')['controls']; let in=index">
              <div [FormGroup]="in">
                ...
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </form>

Note that I am not binding to [FormArrayName] in the line [FormArrayName]="questionsDetail. This should be formArrayName="questionsDetail. Same for choices