1 import { FormGroup } from '@angular/forms'
2 import { BuildFormArgument, BuildFormDefaultValues, FormValidatorService } from './form-validators'
4 export type FormReactiveErrors = { [ id: string ]: string | FormReactiveErrors }
5 export type FormReactiveValidationMessages = {
6 [ id: string ]: { [ name: string ]: string } | FormReactiveValidationMessages
9 export abstract class FormReactive {
10 protected abstract formValidatorService: FormValidatorService
11 protected formChanged = false
14 formErrors: any // To avoid casting in template because of string | FormReactiveErrors
15 validationMessages: FormReactiveValidationMessages
17 buildForm (obj: BuildFormArgument, defaultValues: BuildFormDefaultValues = {}) {
18 const { formErrors, validationMessages, form } = this.formValidatorService.buildForm(obj, defaultValues)
21 this.formErrors = formErrors
22 this.validationMessages = validationMessages
24 this.form.valueChanges.subscribe(() => this.onValueChanged(this.form, this.formErrors, this.validationMessages, false))
27 protected forceCheck () {
28 return this.onValueChanged(this.form, this.formErrors, this.validationMessages, true)
32 return this.onValueChanged(this.form, this.formErrors, this.validationMessages, false)
35 private onValueChanged (
37 formErrors: FormReactiveErrors,
38 validationMessages: FormReactiveValidationMessages,
41 for (const field of Object.keys(formErrors)) {
42 if (formErrors[field] && typeof formErrors[field] === 'object') {
44 form.controls[field] as FormGroup,
45 formErrors[field] as FormReactiveErrors,
46 validationMessages[field] as FormReactiveValidationMessages,
52 // clear previous error message (if any)
53 formErrors[ field ] = ''
54 const control = form.get(field)
56 if (control.dirty) this.formChanged = true
58 // Don't care if dirty on force check
59 const isDirty = control.dirty || forceCheck === true
60 if (control && isDirty && control.enabled && !control.valid) {
61 const messages = validationMessages[ field ]
62 for (const key of Object.keys(control.errors)) {
63 formErrors[ field ] += messages[ key ] + ' '