import { Directive, ElementRef, HostListener } from '@angular/core'; import { ControlValueAccessor } from '@angular/forms'; import { VegaEventManager } from '@globalpayments/vega'; @Directive({ selector: 'vega-value-accessor' }) export class ValueAccessor implements ControlValueAccessor { private onChange: (value: any) => void = () => { /**/ }; private onTouched: () => void = () => { /**/ }; protected lastValue: any; constructor(protected el: ElementRef) {} writeValue(value: any) { this.el.nativeElement.value = this.lastValue = value == null ? '' : value; } handleChangeEvent(value: any, semantics: 'native' | 'vega') { if (VegaEventManager.getSemantics(this.el.nativeElement).namespace === semantics) { const isNumberCompare = typeof value === 'number' || typeof this.lastValue === 'number'; if (isNumberCompare ? String(value) !== String(this.lastValue) : value !== this.lastValue) { this.lastValue = value; this.onChange(value); } } } @HostListener('focusout') _handleBlurEvent() { this.onTouched(); } registerOnChange(fn: (value: any) => void) { this.onChange = fn; } registerOnTouched(fn: () => void) { this.onTouched = fn; } setDisabledState(isDisabled: boolean) { this.el.nativeElement.disabled = isDisabled; } }