Angular 2 - Input mask: the input field displays the formatted value, and the model stores the unformatted value

I am trying to get the values โ€‹โ€‹of an input field / input mask when I enter them, and the actual model retains the original (or otherwise formatted) value. I think phone numbers etc. But for simplicity I use uppercase letters for testing.

I tried a bunch of things, hoping that it would be just like a directive. But it may not seem that the displayed value deviates from the value of the form.

plunk: http://plnkr.co/edit/VH5zn4S8q28CBpFutBlx?p=preview

Here's the directive:

@Directive({ selector: '[uppercase]', host: { '(input)': 'onInputChange()', } }) export class UppercaseDirective { constructor(private model: NgFormControl) { } onInputChange() { let newValue = this.model.value.toUpperCase(); this.model.viewToModelUpdate(newValue); this.model.valueAccessor.writeValue(newValue); } } 

and form:

 <form [ngFormModel]='myForm'> <input [ngFormControl]='myForm.controls.field' uppercase> <div> {{ myForm.value.field }} </div> </form> 
+5
source share
2 answers

Try updating the management link as follows:

 onInputChange() { let newValue = this.model.value.toUpperCase(); this.model.control.updateValue(newValue); } 

See also plunker http://plnkr.co/edit/XYPWYgA8lbg2EdxPqzWj?p=preview

+3
source

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

+1
source

All Articles