Dynamic nested reactive form: ExpressionChangedAfterItHasBeenCheckedError

前端 未结 3 447
萌比男神i
萌比男神i 2021-02-04 02:01

My reactive form is three component levels deep. The parent component creates a new form without any fields and passes it down to child components.

At first the outer fo

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-04 02:13

    import {ChangeDetectorRef} from '@angular/core';
    ....
    
    export class SomeComponent {
    
      form: FormGroup;
    
      constructor(private fb: FormBuilder,
                  private ref: ChangeDetectorRef) {
        this.form = this.fb.group({
          myArray: this.fb.array([])
        });
      }
    
      get myArray(): FormArray {
        return this.form.controls.myArray as FormArray;
      }
    
      addGroup(): void {
        const newGroup = this.fb.group({
          prop1: [''],
          prop2: ['']
        });
    
        this.myArray.push(newGroup);
        this.ref.detectChanges();
      }
    }
    

提交回复
热议问题