import { Directive, effect, ElementRef, Inject, input } from '@angular/core'; import { ValidationErrors } from '@angular/forms'; import { FORM_ERRORS } from './form-validations'; @Directive({ selector: '[appControlError]', standalone: true, }) export class ControlErrorDirective { controlErrors = input(null, { alias: 'appControlError', }); constructor( @Inject(FORM_ERRORS) private errors: any, private element: ElementRef ) { effect(() => { this.checkErrors(this.controlErrors()); }); } private checkErrors(errors: ValidationErrors | readonly { message?: string }[] | null) { if (!errors || (Array.isArray(errors) && errors.length === 0)) { this.element.nativeElement.innerText = ''; return; } if (Array.isArray(errors)) { this.element.nativeElement.innerText = errors[0]?.message ?? ''; return; } this.setError(errors); } private setError(errors: ValidationErrors) { const firstKey = Object.keys(errors)[0]; const getError = this.errors[firstKey] ? this.errors[firstKey] : this.errors[0]; this.element.nativeElement.innerText = getError(errors[firstKey]); } }