Reactive Forms - mark fields as touched
The following function recurses through controls in a form group and gently touches them. Because the controls field is an object, the code call Object.values() on the form group's control field.
/** * Marks all controls in a form group as touched * @param formGroup - The form group to touch */ private markFormGroupTouched(formGroup: FormGroup) { (<any>Object).values(formGroup.controls).forEach(control => { control.markAsTouched(); if (control.controls) { this.markFormGroupTouched(control); } }); }
From Angular 8/9 you can simply use
this.form.markAllAsTouched();
To mark a control and it's descendant controls as touched.
Regarding to @masterwork's answer.I tried that solution, but I got an error when the function tried to dig, recursively, inside a FormGroup, because there is passing a FormControl argument, instead of a FormGroup, at this line:
control.controls.forEach(c => this.markFormGroupTouched(c));
Here is my solution
markFormGroupTouched(formGroup: FormGroup) { (<any>Object).values(formGroup.controls).forEach(control => { if (control.controls) { // control is a FormGroup markFormGroupTouched(control); } else { // control is a FormControl control.markAsTouched(); } });}