I have an easy setup with Angular typed forms.
In the example I built a FormGroup with two FormControls:
- A normal text field with required Validators
- A form Array that contains a FormGroup with a single FormControl that is again just a text.
I also have two buttons where new FormGroups can be added/removed from the FormArray:
export class AppComponent {
formGroup = this.fb.nonNullable.group({
Name: ['', Validators.required],
AppAssignments: this.fb.array(
[] as FormGroup<{
Name: FormControl<string | null>;
}>[]
),
});
constructor(
private fb: FormBuilder,
public changeDetectorRef: ChangeDetectorRef
) {}
public addAppAssignment() {
this.formGroup.controls.AppAssignments.controls.push(
this.fb.group({
Name: new FormControl<string | null>(null, Validators.required),
})
);
this.formGroup.updateValueAndValidity();
this.changeDetectorRef.detectChanges();
}
public removeAppAssignment() {
if (this.formGroup.controls.AppAssignments.length > 0) {
this.formGroup.controls.AppAssignments.removeAt(
this.formGroup.controls.AppAssignments.length - 1
);
}
}
}
I am expecting the "Submit"-Button on the bottom of the form to be disabled/enabled depending on the status of the FormGroup.
However, adding Elements to the FormArray does not invalidate the FormControl.
When I debug the whole thing, I can see that after adding new FormControls to the FormArray, the FormArray is "VALID", even though some of the FormGroups inside are not valid anymore.
How can this be?