Search code examples
ionic3angular5angular4-forms

Dynamically formArray creating


I have a formgroup name studentRegistrationForm. In this form i want to create dynamically studentList array but i can not done this.

ngOnInit(){
 this.studentRegistrationForm = this.formBuilder.group({
      session: ['', [Validators.required]],
      semester: ['', [Validators.required]],
      students: ['',[Validators.required]],
      studentList: this.formBuilder.array([
      ]),
    });

    let control = <FormArray>this.studentRegistrationForm.controls['studentList'];


    this.studentRegistrationForm.valueChanges
      .subscribe( data => {
        if(data.semester  && data.session && data.students){
          control.push(this.createStudent());
        }

      });
}

  createStudent() {
    return new FormGroup({
      id: new FormControl('', Validators.required),
      email: new FormControl('',Validators.required)
    })
  }

here is my error picture


Solution

  • As noted in the comments, your issue is that you're subscribing to form changes, which then adds more data to the form, which triggers form changes, and so on until you reach the stack limit.

    Without further context to what your use case, my suggestion would be to remove the subscription to form changes and instead add a button for adding a new student to the list, which you can disable unless the current form is valid (similar to the logic that you already have in place):

    <div formArrayName="studentList" class="well well-lg">
        <div *ngFor="let student of students.controls; let i=index" [formGroupName]="i">
            <label for="id">ID:</label><input formControlName="id">
            <label for="id">EMail:</label><input formControlName="email">
        </div>
        <button type="button" (click)="doCreateStudent()" [disabled]="!studentRegistrationForm.valid">Add Student</button>
    </div>
    

    As you have validators defined for semester, session and students fields already, you can just use studentRegistrationForm.valid to test validity before allowing a new student to be added.

    Here's a minimal stackblitz demonstrating your code working without the error: