import { Directive , ElementRef , EventEmitter , forwardRef , HostListener , Output , ChangeDetectorRef } from '@angular/core' ; import { ControlValueAccessor , NG_VALUE_ACCESSOR } from '@angular/forms' ; export const TOOLBAR_SEARCH_VALUE_ACCESSOR = { provide : NG_VALUE_ACCESSOR , useExisting : forwardRef ( ( ) => ToolbarSearchFieldDirective ) , multi : true } ; @ Directive ( { selector : '[uxToolbarSearchField]' , providers : [ TOOLBAR_SEARCH_VALUE_ACCESSOR ] } ) export class ToolbarSearchFieldDirective implements ControlValueAccessor { /** Emit whenever the escape key is pressed */ @ Output ( ) cancel = new EventEmitter < void > ( ) ; /** Emit whenever the enter key is pressed */ @ Output ( ) submitted = new EventEmitter < string > ( ) ; /** Get the current value of the input control */ get text ( ) : string { return this . _elementRef . nativeElement . value ; } /** For use with the Forms and ReactiveForms */ private onTouchedCallback : ( ) => void = ( ) => { } ; /** Call this function with the latest value to update ngModel or formControl name */ private onChangeCallback : ( _ : any ) => void = ( ) => { } ; constructor ( private _elementRef , private readonly _changeDetector ) { } focus ( ) { this . onTouchedCallback ( ) ; requestAnimationFrame ( ( ) => this . _elementRef . nativeElement . focus ( ) ) ; } blur ( ) { requestAnimationFrame ( ( ) => this . _elementRef . nativeElement . blur ( ) ) ; } /** Clear the input, if we have an ngModel reset its value otherwise just set the input value to empty */ clear ( ) { this . setValue ( '' ) ; } @ HostListener ( 'keydown.enter' ) onEnter ( ) { this . submitted . emit ( this . text ) ; } @ HostListener ( 'keydown.escape' ) onEscape ( ) { this . _elementRef . nativeElement . blur ( ) ; this . cancel . emit ( ) ; } @ HostListener ( 'input' ) onInput ( ) { this . setValue ( this . text ) ; } /** Update the input value based on ngModel or formControl */ writeValue ( value ) { this . setValue ( value ) ; this . _changeDetector . markForCheck ( ) ; } /** Register a function to update form control */ registerOnChange ( fn ) { this . onChangeCallback = fn ; } /** Register a function to mark form control as touched */ registerOnTouched ( fn ) { this . onTouchedCallback = fn ; } /** Update the value in all required places */ private setValue ( value ) { if ( ! value ) { value = '' ; } this . onChangeCallback ( value ) ; this . _elementRef . nativeElement . value = value ; } }