2 import { FormGroup } from '@angular/forms'
3 import { wait } from '@root-helpers/utils'
4 import { BuildFormArgument, BuildFormDefaultValues } from '../form-validators/form-validator.model'
5 import { FormValidatorService } from './form-validator.service'
7 export type FormReactiveErrors = { [ id: string ]: string | FormReactiveErrors }
8 export type FormReactiveValidationMessages = {
9 [ id: string ]: { [ name: string ]: string } | FormReactiveValidationMessages
12 export abstract class FormReactive {
13 protected abstract formValidatorService: FormValidatorService
14 protected formChanged = false
17 formErrors: any // To avoid casting in template because of string | FormReactiveErrors
18 validationMessages: FormReactiveValidationMessages
20 buildForm (obj: BuildFormArgument, defaultValues: BuildFormDefaultValues = {}) {
21 const { formErrors, validationMessages, form } = this.formValidatorService.buildForm(obj, defaultValues)
24 this.formErrors = formErrors
25 this.validationMessages = validationMessages
27 this.form.statusChanges.subscribe(async () => {
28 // FIXME: remove when https://github.com/angular/angular/issues/41519 is fixed
29 await this.waitPendingCheck()
31 this.onStatusChanged(this.form, this.formErrors, this.validationMessages)
35 protected async waitPendingCheck () {
36 if (this.form.status !== 'PENDING') return
38 // FIXME: the following line does not work: https://github.com/angular/angular/issues/41519
39 // return firstValueFrom(this.form.statusChanges.pipe(filter(status => status !== 'PENDING')))
40 // So we have to fallback to active wait :/
44 } while (this.form.status === 'PENDING')
47 protected forceCheck () {
48 this.onStatusChanged(this.form, this.formErrors, this.validationMessages, false)
51 private onStatusChanged (
53 formErrors: FormReactiveErrors,
54 validationMessages: FormReactiveValidationMessages,
57 for (const field of Object.keys(formErrors)) {
58 if (formErrors[field] && typeof formErrors[field] === 'object') {
60 form.controls[field] as FormGroup,
61 formErrors[field] as FormReactiveErrors,
62 validationMessages[field] as FormReactiveValidationMessages
67 // clear previous error message (if any)
68 formErrors[field] = ''
69 const control = form.get(field)
71 if (control.dirty) this.formChanged = true
73 if (!control || (onlyDirty && !control.dirty) || !control.enabled || !control.errors) continue
75 const staticMessages = validationMessages[field]
76 for (const key of Object.keys(control.errors)) {
77 const formErrorValue = control.errors[key]
79 // Try to find error message in static validation messages first
80 // Then check if the validator returns a string that is the error
81 if (staticMessages[key]) formErrors[field] += staticMessages[key] + ' '
82 else if (typeof formErrorValue === 'string') formErrors[field] += control.errors[key]
83 else throw new Error('Form error value of ' + field + ' is invalid')