Skip to content

Instantly share code, notes, and snippets.

@burntblark
Created November 16, 2018 16:35
Show Gist options
  • Save burntblark/b9e103a9e898ac02507eb2fe3a40e94d to your computer and use it in GitHub Desktop.
Save burntblark/b9e103a9e898ac02507eb2fe3a40e94d to your computer and use it in GitHub Desktop.
An Angular Attribute Directive to ensure title cases.
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