blob: 0bb7d25e6f5c606da996ae66195930b9262f14bc (
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
41
42
43
44
45
46
47
48
49
50
51
|
import { FormGroup } from '@angular/forms'
import { BuildFormArgument, BuildFormDefaultValues, FormValidatorService } from '@app/shared/forms/form-validators/form-validator.service'
export type FormReactiveErrors = { [ id: string ]: string }
export type FormReactiveValidationMessages = {
[ id: string ]: {
[ name: string ]: string
}
}
export abstract class FormReactive {
protected abstract formValidatorService: FormValidatorService
protected formChanged = false
form: FormGroup
formErrors: FormReactiveErrors
validationMessages: FormReactiveValidationMessages
buildForm (obj: BuildFormArgument, defaultValues: BuildFormDefaultValues = {}) {
const { formErrors, validationMessages, form } = this.formValidatorService.buildForm(obj, defaultValues)
this.form = form
this.formErrors = formErrors
this.validationMessages = validationMessages
this.form.valueChanges.subscribe(() => this.onValueChanged(false))
}
protected onValueChanged (forceCheck = false) {
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[ field ] = ''
const control = this.form.get(field)
if (control.dirty) this.formChanged = true
// Don't care if dirty on force check
const isDirty = control.dirty || forceCheck === true
if (control && isDirty && !control.valid) {
const messages = this.validationMessages[ field ]
for (const key in control.errors) {
this.formErrors[ field ] += messages[ key ] + ' '
}
}
}
}
protected forceCheck () {
return this.onValueChanged(true)
}
}
|