import { ElementRef, Injector } from '@angular/core'; import { NgControl } from '@angular/forms'; import { hostElementError } from '../exceptions'; import { ControlDetector } from '../../../interfaces'; export enum FormatType{ uppercase, lowercase, capital, titlecase, trim, combine, normalize, } export class Format implements ControlDetector { native: HTMLInputElement | HTMLTextAreaElement; constructor( protected ref: ElementRef, protected injector: Injector, ){this.native = this.ref.nativeElement;}; private _uppercase(value: string): string { return value.toUpperCase(); } private _lowercase(value: string): string { return value.toLowerCase(); } private _capital(value: string): string { return value[0].toUpperCase() + value.slice(1); } private _titlecase(value: string): string { return value.split(' ').map(word => word ? this._capital(word) : '').join(' '); } private _trim(value: string): string { return value.trim(); } private _combine(value: string): string { return value.split(' ').join(''); } private _normalize(value: string): string { return value.split(' ').filter(str => str).join(' '); } protected blurHandler(formatType: FormatType | Function): void { const isCompitable = this.native instanceof HTMLInputElement || this.native instanceof HTMLTextAreaElement; if(!isCompitable)hostElementError(this.native.tagName); const valueAtBlur: string = this.native.value; let formattedValue: string; switch (formatType){ case FormatType.uppercase: formattedValue = this._uppercase(valueAtBlur); break; case FormatType.lowercase: formattedValue = this._lowercase(valueAtBlur); break; case FormatType.capital: formattedValue = this._capital(valueAtBlur); break; case FormatType.titlecase: formattedValue = this._titlecase(valueAtBlur); break; case FormatType.trim: formattedValue = this._trim(valueAtBlur); break; case FormatType.combine: formattedValue = this._combine(valueAtBlur); break; case FormatType.normalize: formattedValue = this._normalize(valueAtBlur); break; /* --- for custom callbacks --- */ default: formattedValue = formatType(valueAtBlur) } this.detectAndSet(this.native,formattedValue); } public detectAndSet(elem, value){ let abstractController: NgControl; try{ abstractController = this.injector.get(NgControl); abstractController.control.setValue(value) }catch{ elem.value = value; } } }