0

I'm using Angular 8.

I have the following reactive form group.

this.form = this.fb.group({
  query: ['', [
    Validators.required
  ]]
});

And in the HTML

<form [formGroup]="form" (submit)="onSubmit">
    <textarea formControlName="query" placeholder="SELECT ..."></textarea>
    <form-errors [control]="f.query"></form-errors>

    <button type="submit">Submit</button>
</form>

The form-errors is a custom template which displays error message which has following method to trigger validation check on the control.

shouldShowErrors(): boolean {
    return this.control && 
           this.control.errors && 
           (this.control.dirty || this.control.touched);
}

Thus validation is triggered when control is touched or changed.

How can I trigger validation check on submit of the form? How can I access the form inside the form-errors component by the passed control?

Anna
  • 2,988
  • 3
  • 15
  • 29
Anuj TBE
  • 9,198
  • 27
  • 136
  • 285

1 Answers1

0

You can mark all controls as touched on submit button click like create a method for that and call it

 public markFormGroupTouched(formGroup: FormGroup) {
    Object.values(formGroup.controls).forEach(control => {
      control.markAsTouched();

      if (control.controls) {
          control.controls.forEach(c => this.markFormGroupTouched(c));
      }
    });
  }
  this.markFormGroupTouched(this.form);

demo

jitender
  • 10,238
  • 1
  • 18
  • 44
  • 1
    is `control.controls` for nested form group? Because it is giving error `AbstractControl has no attribute controls`. I solved it by making all `formGroup` touched by `formGroup.markAllAsTouched()` and its working. – Anuj TBE Oct 20 '19 at 08:10