]>
Commit | Line | Data |
---|---|---|
df98563e | 1 | import { FormGroup } from '@angular/forms' |
d18d6478 C |
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 | } | |
4b2f33f3 C |
10 | |
11 | export abstract class FormReactive { | |
d18d6478 | 12 | protected abstract formValidatorService: FormValidatorService |
772d5642 | 13 | protected formChanged = false |
4b2f33f3 | 14 | |
d18d6478 C |
15 | form: FormGroup |
16 | formErrors: FormReactiveErrors | |
17 | validationMessages: FormReactiveValidationMessages | |
4b2f33f3 | 18 | |
d18d6478 C |
19 | buildForm (obj: BuildFormArgument, defaultValues: BuildFormDefaultValues = {}) { |
20 | const { formErrors, validationMessages, form } = this.formValidatorService.buildForm(obj, defaultValues) | |
4b2f33f3 | 21 | |
d18d6478 C |
22 | this.form = form |
23 | this.formErrors = formErrors | |
24 | this.validationMessages = validationMessages | |
25 | ||
b4a929ac | 26 | this.form.valueChanges.subscribe(() => this.onValueChanged(false)) |
4b2f33f3 | 27 | } |
bf57d5ee | 28 | |
d18d6478 | 29 | protected onValueChanged (forceCheck = false) { |
bf57d5ee C |
30 | for (const field in this.formErrors) { |
31 | // clear previous error message (if any) | |
d18d6478 | 32 | this.formErrors[ field ] = '' |
df98563e | 33 | const control = this.form.get(field) |
bf57d5ee | 34 | |
772d5642 C |
35 | if (control.dirty) this.formChanged = true |
36 | ||
d18d6478 C |
37 | // Don't care if dirty on force check |
38 | const isDirty = control.dirty || forceCheck === true | |
39 | if (control && isDirty && !control.valid) { | |
40 | const messages = this.validationMessages[ field ] | |
bf57d5ee | 41 | for (const key in control.errors) { |
d18d6478 | 42 | this.formErrors[ field ] += messages[ key ] + ' ' |
bf57d5ee C |
43 | } |
44 | } | |
45 | } | |
46 | } | |
d18d6478 C |
47 | |
48 | protected forceCheck () { | |
49 | return this.onValueChanged(true) | |
50 | } | |
4b2f33f3 | 51 | } |