I would like to markAsDirty
all the controls inside of a FormGroup
.
Based on @Keenan Diggs answer I wrote a generic function to traverse a flat or nested form, which accepts an operation to be performed against each form control:
export function traverseForm(
form: FormGroup | FormArray,
fn: ((c: AbstractControl, name: string, path: string) => void),
initialPath: string = '') {
Object.keys(form.controls).forEach((key: string) => {
const abstractControl = form.controls[key];
const path = initialPath ? (initialPath + '.' + key) : key;
fn(abstractControl, key, path);
if (abstractControl instanceof FormGroup || abstractControl instanceof FormArray) {
traverseForm(abstractControl, fn, path);
}
});
}
To be used like this:
const markAsDirty = (ctrl: AbstractControl) => {
if (!(abstractControl instanceof FormGroup) && !(abstractControl instanceof FormArray)) {
abstractControl.markAsDirty();
}
}
traverseForm(form, markAsDirty);
Object.keys( this.registerForm.controls).forEach(key => {
this.registerForm.controls[key].markAsDirty();
});
This is what working for me
private markFormGroupTouched(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach((key) => {
const control = formGroup.controls[key];
control.markAsDirty();
if ((control instanceof FormGroup)) {
this.markFormGroupTouched(control);
}
});
}