Search code examples
angularangular-reactive-formsformarrayangular2-formbuilderangular-formbuilder

Angular FormAray of compnent


I'm trying to do a an array of the child component reactive form. every time I edit in the child (questionForm) it get updated in the parent (adminForm), I have been trying to do this for 2 weeks. so please if you can help I appreciate it I left some related code from what I've been working on

parent.ts

 this.adminForm=this.fb.group({
      //SurveyName:this.nameForm.getData(),
      Questions: this.fb.array([
      ])
    });

get questions() {
    return this.adminForm.controls["Questions"] as FormArray;
  }
addQuestion() {
    //this.questions.push();
  }

parent.html

<div *ngFor="let alias of questions.controls; let i=index">
            <app-question></app-question>
</div>
 <a (click)="addQuestion()">Add question</a>

child.ts

this.questionForm = this.fb.group({
      question: [''],
      type: ['Checkboxes'],
      required: [false],
      options: this.fb.array([
        this.fb.control('')
      ])
    });

Solution

  • when you use a child to control a FormGroup, there are two aproach:

    1. Create the formGroup in parent and pass to child using @Input
    2. Create the formGroup in child and pass to parent using @Output

    For me is more confortable using the first aproach

    If you has in your parent

    getGroup(){
      return this.fb.group({
          question: [''],
          type: ['Checkboxes'],
          required: [false],
          options: this.fb.array([
            this.fb.control('')
          ])
        });
    }
    //when add a question, always in parent
    addQuestion() {
      this.questions.push(this.getGroup());
    }
    

    Your child simply has

    formGroup:FormGroup;
    @Input('form') set form(value){
        this.formGroup=value as FormGroup
    }
    

    the hml like another formGroup

       <form [formGroup]="formGroup">
         <input formControlName="question">
         ....
       </form>
    

    And you use in parent:

    <div *ngFor="let alias of questions.controls; let i=index">
         <app-question [form]=questions.at(i)></app-question>
    </div>