Dynamic nested reactive form: ExpressionChangedAfterItHasBeenCheckedError

前端 未结 3 456
萌比男神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:33

    I had the same scenario and same issue in Angular 9 and above solution works fine. I tweaked it a little bit: synchroinously adding the control without validators and adding the required validators asynchronously... Because I needed the controls immediately otherwise I got an error cannot find formControl ....

    This is my solution based on the accepted answer above:

    const resolvedPromise = Promise.resolve(null);
    @Component({
      selector: 'password-input',
      templateUrl: './password-input.component.html',
      styleUrls: ['./password-input.component.css']
    })
    export class PasswordInputComponent implements OnInit {
      @Input() parentFormGroup : FormGroup;
      @Input() controlName : string = 'password';
      @Input() placeholder : string = 'Password';
      @Input() label : string = null;
    
      ngOnInit(): void {
        this.parentFormGroup.addControl(this.controlName, new FormControl(null));
       
        resolvedPromise.then( () => {
          this.parentFormGroup.get(this.controlName).setValidators(Validators.required)
          this.parentFormGroup.get(this.controlName).updateValueAndValidity();
        });
      }
    

提交回复
热议问题