]>
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 |
4b2f33f3 | 13 | |
d18d6478 C |
14 | form: FormGroup |
15 | formErrors: FormReactiveErrors | |
16 | validationMessages: FormReactiveValidationMessages | |
4b2f33f3 | 17 | |
d18d6478 C |
18 | buildForm (obj: BuildFormArgument, defaultValues: BuildFormDefaultValues = {}) { |
19 | const { formErrors, validationMessages, form } = this.formValidatorService.buildForm(obj, defaultValues) | |
4b2f33f3 | 20 | |
d18d6478 C |
21 | this.form = form |
22 | this.formErrors = formErrors | |
23 | this.validationMessages = validationMessages | |
24 | ||
25 | this.form.valueChanges.subscribe(data => this.onValueChanged(false)) | |
4b2f33f3 | 26 | } |
bf57d5ee | 27 | |
d18d6478 | 28 | protected onValueChanged (forceCheck = false) { |
bf57d5ee C |
29 | for (const field in this.formErrors) { |
30 | // clear previous error message (if any) | |
d18d6478 | 31 | this.formErrors[ field ] = '' |
df98563e | 32 | const control = this.form.get(field) |
bf57d5ee | 33 | |
d18d6478 C |
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 ] | |
bf57d5ee | 38 | for (const key in control.errors) { |
d18d6478 | 39 | this.formErrors[ field ] += messages[ key ] + ' ' |
bf57d5ee C |
40 | } |
41 | } | |
42 | } | |
43 | } | |
d18d6478 C |
44 | |
45 | protected forceCheck () { | |
46 | return this.onValueChanged(true) | |
47 | } | |
4b2f33f3 | 48 | } |