Honestly, I'm still studying angular2, and the technology is still immature to say that this is the best way to do this, but after playing with it:
import {Directive, ElementRef, Output, EventEmitter} from '@angular/core'; import {NgFormControl} from '@angular/common'; @Directive({ selector: '[uppercase]', host: { '(input)': 'onInputChange()', } }) export class UppercaseDirective { @Output() onChange = new EventEmitter(); rawValue: string = ''; constructor(private model: NgFormControl, private elementRef: ElementRef) { } onInputChange() { let str = this.model.value; this.rawValue = this.rawValue.substring(0, str.length) + str.substring(this.rawValue.length, str.length); let newValue = this.rawValue.toUpperCase(); this.model.viewToModelUpdate(newValue); this.model.valueAccessor.writeValue(newValue); this.onChange.emit(this.rawValue); } }
then you can get it like this:
<input [ngFormControl]='myForm.controls.field' uppercase (onChange)="raw = $event"> <div> {{ raw }} </div>
Since whenever you update the model, the variable will change. You must do this separately. Tried this in your plnkr and it worked.
EDIT: It might take some work for different scenarios, though haha
source share