At least in my experience, I found two of the answers here insightful, but not working on their own: from Thierry Templier (with first comment as well), and from cal.
I put together parts of both, and came up with this version, which is now working with Angular 4.1.1 in a reactive form:
import { Directive, Renderer, ElementRef, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, DefaultValueAccessor } from '@angular/forms';
const LOWERCASE_INPUT_CONTROL_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => LowerCaseInputDirective),
multi: true,
};
@Directive({
selector: 'input[lowercase]',
host: {
// When the user updates the input
'(input)': 'onInput($event.target.value)',
'(blur)': 'onTouched()',
},
providers: [
LOWERCASE_INPUT_CONTROL_VALUE_ACCESSOR,
],
})
export class LowerCaseInputDirective extends DefaultValueAccessor {
constructor(renderer: Renderer, elementRef: ElementRef) {
super(renderer, elementRef, false);
}
writeValue(value: any): void {
const transformed = this.transformValue(value);
super.writeValue(transformed);
}
onInput(value: any): void {
const transformed = this.transformValue(value);
super.writeValue(transformed);
this.onChange(transformed);
}
private transformValue(value: any): any {
const result = value && typeof value === 'string'
? value.toLowerCase()
: value;
return result;
}
}
This is for lower-case, but everything holds for upper-case as well, just rename directive, replace within selector
and transformValue
.
Edit:
A straightforward usage example from HTML code using such directive:
<input id="myField"
formControlName="myField"
type="text" class="form-control required"
lowercase>
<input type="text" #input [value]="input.value.toUpperCase()" />
– Yokotext-transform:uppercase;
to make it uppercase? – Ringsmuth