Created
November 16, 2018 16:35
-
-
Save burntblark/b9e103a9e898ac02507eb2fe3a40e94d to your computer and use it in GitHub Desktop.
An Angular Attribute Directive to ensure title cases.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, ElementRef, forwardRef, Renderer2, HostListener } from '@angular/core'; | |
import { NG_VALUE_ACCESSOR, DefaultValueAccessor } from '@angular/forms'; | |
const TITLECASE_INPUT_CONTROL_VALUE_ACCESSOR = { | |
provide: NG_VALUE_ACCESSOR, | |
useExisting: forwardRef(() => TitlecaseInputDirective), | |
multi: true, | |
}; | |
@Directive({ | |
selector: 'input[appTitlecaseInput]', | |
providers: [ | |
TITLECASE_INPUT_CONTROL_VALUE_ACCESSOR, | |
], | |
}) | |
export class TitlecaseInputDirective extends DefaultValueAccessor { | |
constructor(renderer: Renderer2, elementRef: ElementRef) { | |
super(renderer, elementRef, false); | |
} | |
writeValue(value: any): void { | |
const transformed = this._transformValue(value); | |
super.writeValue(transformed); | |
} | |
@HostListener('input', ['$event']) | |
onInputChange(e: any): void { | |
console.log(e); | |
if (e.data === ' ') { // Until space entered | |
const transformed = this._transformValue(e.target.value); | |
super.writeValue(transformed); | |
this.onChange(transformed); | |
} | |
} | |
@HostListener('blur', ['$event']) | |
onInputBlur(e: any): void { | |
const transformed = this._transformValue(e.target.value); | |
super.writeValue(transformed); | |
this.onChange(transformed); | |
} | |
private _transformValue(value: any) { | |
const result = value && typeof value === 'string' | |
? this._toTitleCase(value) | |
: value; | |
return result; | |
} | |
private _toTitleCase(value) { | |
return value.replace( | |
/\b(?!a\b|an\b|the\b|and\b|on\b)\w\S*/g, | |
function (title) { | |
return title.charAt(0).toUpperCase() + title.substr(1).toLowerCase(); | |
} | |
); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment