1 import { FormGroup } from '@angular/forms'
2 import { BuildFormArgument, BuildFormDefaultValues, FormValidatorService } from '@app/shared/forms/form-validators/form-validator.service'
4 export type FormReactiveErrors = { [ id: string ]: string }
5 export type FormReactiveValidationMessages = {
7 [ name: string ]: string
11 export abstract class FormReactive {
12 protected abstract formValidatorService: FormValidatorService
13 protected formChanged = false
16 formErrors: FormReactiveErrors
17 validationMessages: FormReactiveValidationMessages
19 buildForm (obj: BuildFormArgument, defaultValues: BuildFormDefaultValues = {}) {
20 const { formErrors, validationMessages, form } = this.formValidatorService.buildForm(obj, defaultValues)
23 this.formErrors = formErrors
24 this.validationMessages = validationMessages
26 this.form.valueChanges.subscribe(data => this.onValueChanged(false))
29 protected onValueChanged (forceCheck = false) {
30 for (const field in this.formErrors) {
31 // clear previous error message (if any)
32 this.formErrors[ field ] = ''
33 const control = this.form.get(field)
35 if (control.dirty) this.formChanged = true
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 ]
41 for (const key in control.errors) {
42 this.formErrors[ field ] += messages[ key ] + ' '
48 protected forceCheck () {
49 return this.onValueChanged(true)