import { AfterViewInit , Component , Inject , InjectionToken , Input , OnDestroy , Optional } from '@angular/core' ; import { FormGroupDirective , NgControl , NgForm } from '@angular/forms' ; import { Subject , merge as observableMerge } from 'rxjs' ; import { delay , takeUntil } from 'rxjs/operators' ; import { ObFormControlStateDirective } from '../form-control-state/form-control-state.directive' ; import { ObErrorMessagesService } from './error-messages.service' ; import { ObThemeService } from '../theme.service' ; import { ObParentFormDirective } from '../nested-form/parent-form.directive' ; import { WINDOW } from '../utilities' ; export const DISABLE_NGB_ERRORS = new InjectionToken < boolean > ( 'ENABLE_NGB_ERRORS' ) ; deprecated @ Component ( { selector : 'ob-error-messages' , exportAs : 'obErrorMessages' , templateUrl : './error-messages.component.html' } ) export class ObErrorMessagesComponent implements AfterViewInit , OnDestroy { @ Input ( ) control : NgControl ; @ Input ( ) disableNgb : boolean ; errors : { key : string ; params : { [ param ] : any ; } ; } [ ] = [ ] ; private readonly form : NgForm | FormGroupDirective ; private readonly unsubscribe = new Subject ( ) ; constructor ( private readonly errorMessagesService , theme , @ Optional ( ) private readonly formGroup , @ Optional ( ) ngForm , @ Optional ( ) formGroupDirective , @ Optional ( ) private readonly parent , @ Inject ( WINDOW ) private readonly window , @ Optional ( ) @ Inject ( DISABLE_NGB_ERRORS ) disableNgb ) { this . disableNgb = this . disableNgb ?? disableNgb ?? false ; theme . deprecated ( 'error messages' , 'form-field/overview#error-messages' ) ; this . form = ngForm || formGroupDirective ; if ( ! this . form ) { throw Error ( 'You need either a NgForm or a FormGroupDirective for the ErrorMessagesComponent' ) ; } } ngAfterViewInit ( ) { this . control = this . control ? this . control : this . formGroup . ngControl ; observableMerge ( this . control . statusChanges , this . form . ngSubmit ) . pipe ( takeUntil ( this . unsubscribe ) , delay ( 0 ) ) . subscribe ( ( ) => this . generateErrorMessages ( ) ) ; if ( this . parent ) { this . parent . submit$ . subscribe ( ( ) => this . generateErrorMessages ( true ) ) ; } this . delayMessageGenerationForReactiveForms ( ) ; } ngOnDestroy ( ) { this . unsubscribe . next ( ) ; this . unsubscribe . complete ( ) ; } private generateErrorMessages ( submitted = false ) { const pristineValidation = this . formGroup ? this . formGroup . pristineValidation : false ; if ( this . control . invalid && ( submitted || this . form . submitted || ! this . control . pristine || pristineValidation ) ) { this . errors = this . errorMessagesService . createMessages ( this . control , this . disableNgb ) ; } else { this . errors = [ ] ; } } private delayMessageGenerationForReactiveForms ( ) { if ( this . form instanceof FormGroupDirective ) { this . window . setTimeout ( ( ) => this . generateErrorMessages ( ) , 0 ) ; } } }