Joyce Brum
Joyce Brum

Reputation: 23

How can I add a invalid Form Control in a Form Array without compromise its funcionality

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)
}

Upvotes: 2

Views: 1362

Answers (1)

Frederick
Frederick

Reputation: 872

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();
}

Upvotes: 2

Related Questions