Reactive Forms - mark fields as touched

后端 未结 19 1514
旧时难觅i
旧时难觅i 2020-12-04 23:15

I am having trouble finding out how to mark all form\'s fields as touched. The main problem is that if I do not touch fields and try to submit form - validation error in not

19条回答
  •  攒了一身酷
    2020-12-04 23:41

    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) {
     (Object).values(formGroup.controls).forEach(control => {
       if (control.controls) { // control is a FormGroup
         markFormGroupTouched(control);
       } else { // control is a FormControl
         control.markAsTouched();
       }
     });
    }
    

提交回复
热议问题