aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/forms/form-reactive.ts
blob: a5732e083a647422335ae176a797477e7257acbb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { FormGroup } from '@angular/forms';

export abstract class FormReactive {
  abstract form: FormGroup;
  abstract formErrors: Object;
  abstract validationMessages: Object;

  abstract buildForm(): void;

  protected onValueChanged(data?: any) {
    for (const field in this.formErrors) {
      // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = this.form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  // Same as onValueChanged but force checking even if the field is not dirty
  protected forceCheck() {
    for (const field in this.formErrors) {
      // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = this.form.get(field);

      if (control && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }
}