import { Directive, ElementRef, HostListener, Input, Injector, OnChanges, SimpleChanges } from '@angular/core'; import { NgControl } from '@angular/forms'; import { ControlDetector } from '../../interfaces'; @Directive({ selector: '[ang-prepend]' }) export class PrependDirective implements OnChanges, ControlDetector { @Input('ang-prepend') prefix: string; lastValidValue: string; native: HTMLInputElement; constructor(private ref: ElementRef, private injector: Injector,){ this.native = this.ref.nativeElement } detectAndSet(elem,value){ let abstractController: NgControl; try{ abstractController = this.injector.get(NgControl); abstractController.control.setValue(value); } catch{ elem.value = value; } } @HostListener('input') onKeyDown(){ if(this.native.value.startsWith(this.prefix) || this.prefix == null){ this.lastValidValue = this.native.value; }else{ this.native.value = this.lastValidValue; } } ngOnChanges(changes: SimpleChanges){ let {previousValue: prevPrefix, currentValue: currPrefix} = changes.prefix; if(currPrefix == null){ currPrefix = '' } setTimeout(() => { const newValue = prevPrefix ? this.native.value.replace(prevPrefix,currPrefix): currPrefix + this.native.value; this.detectAndSet(this.native,newValue); this.lastValidValue = this.native.value; }) } }