2

I want to create a dynamic form which add Form Controls (a required form control) to a Form Array.

The Form Control is invalid because it needs to be filled by the user (it is blank)

But when I add the form control, I get an error

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ng-valid: true'. Current value: 'ng-valid:false'

in the console.

add(formControl) {
    (this.formGroup.get('array') asFormArray).push(formControl)
}

1 Answer 1

2

You just need to manually call change detection after adding the invalid child form. Change detection works top-down. And judging by that error, when the button click's (or whatever you're using to add the new form's) change detection cycle runs, it has already checked the form validity by the time it gets to your newly added invalid child form. Manually calling it after the adding the new form tells Angular that a second change detection cycle will be needed because an expression in a higher up element has most likely changed.

constructor(private readonly cdr: ChangeDetectorRef) {}

add(formControl) {
  (this.formGroup.get('array') asFormArray).push(formControl);
  this.cdr.detectChanges();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.