]>
Commit | Line | Data |
---|---|---|
1 | import { FormGroup } from '@angular/forms' | |
2 | import { BuildFormArgument, BuildFormDefaultValues, FormValidatorService } from '@app/shared/forms/form-validators/form-validator.service' | |
3 | ||
4 | export type FormReactiveErrors = { [ id: string ]: string } | |
5 | export type FormReactiveValidationMessages = { | |
6 | [ id: string ]: { | |
7 | [ name: string ]: string | |
8 | } | |
9 | } | |
10 | ||
11 | export abstract class FormReactive { | |
12 | protected abstract formValidatorService: FormValidatorService | |
13 | ||
14 | form: FormGroup | |
15 | formErrors: FormReactiveErrors | |
16 | validationMessages: FormReactiveValidationMessages | |
17 | ||
18 | buildForm (obj: BuildFormArgument, defaultValues: BuildFormDefaultValues = {}) { | |
19 | const { formErrors, validationMessages, form } = this.formValidatorService.buildForm(obj, defaultValues) | |
20 | ||
21 | this.form = form | |
22 | this.formErrors = formErrors | |
23 | this.validationMessages = validationMessages | |
24 | ||
25 | this.form.valueChanges.subscribe(data => this.onValueChanged(false)) | |
26 | } | |
27 | ||
28 | protected onValueChanged (forceCheck = false) { | |
29 | for (const field in this.formErrors) { | |
30 | // clear previous error message (if any) | |
31 | this.formErrors[ field ] = '' | |
32 | const control = this.form.get(field) | |
33 | ||
34 | // Don't care if dirty on force check | |
35 | const isDirty = control.dirty || forceCheck === true | |
36 | if (control && isDirty && !control.valid) { | |
37 | const messages = this.validationMessages[ field ] | |
38 | for (const key in control.errors) { | |
39 | this.formErrors[ field ] += messages[ key ] + ' ' | |
40 | } | |
41 | } | |
42 | } | |
43 | } | |
44 | ||
45 | protected forceCheck () { | |
46 | return this.onValueChanged(true) | |
47 | } | |
48 | } |