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