joh*_*ith 5 model-view-controller model reactive-programming form-control angular
我正在使用反应形式方法。我有一个具有对应的formControl对象的输入字段,并且在键入时我正在对值进行格式化-使所有输入大写。
那当然工作得很好-在视图和formControl中也会更新该值。
The issue is That I would like to send to server the original value and not the formmated value (uppercase)
So I need something like value, and value for display in the formControl object.
See plunker - formatting value formControl
template:
<input type="text"
class="form-control"
(blur)="handleOnBlur($event)"
(input)="onChange($event)"
formControlName="name">
Run Code Online (Sandbox Code Playgroud)
model:
valueForModel: string;
valueForDisplay: string;
public myForm: FormGroup;
onChange(event) {
const value = event.target.value;
this.valueForModel = value;
this.valueForDisplay = value.toUpperCase();
event.target.value = this.valueForDisplay;
}
handleOnBlur(event) {
consol.log(this.valueForModel);
// Herer I'm calling the sever and the server actually works good
// server return back the updated value - but it then override my value
in the dom
// the value for display value
}
ngOnInit() {
this.myForm = this._fb.group({
name: ['', [<any>Validators.required,
<any>Validators.minLength(5)]],
});
}
Run Code Online (Sandbox Code Playgroud)
Can't find anything to help. any suggestion will be appreciated.
这是我的解决方案,它使用附加的data-model-valueHTML 元素属性来存储模型值。
HTML:
<form [formGroup]="myForm">
<input formControlName="myInput" #inputRef >
</form>
Run Code Online (Sandbox Code Playgroud)
TS:
....
@ViewChild('inputRef') inputRef;
....
ngOnInit() {
this.myForm = this._fb.group({
myInput: ['', [Validators.required]]
});
// listen to input changes
this.myForm.get('myInput').valueChanges.subscribe(val => {
const elRef = this.inputRef.nativeElement;
// get stored original unmodified value (not including last change)
const orVal = elRef.getAttribute('data-model-value') || '';
// modify new value to be equal to the original input (including last change)
val = val.replace(orVal.toUpperCase(), orVal);
// store original unmodified value (including last change)
elRef.setAttribute('data-model-value', val);
// set view value using DOM value property
elRef.value = val.toUpperCase();
// update model without emitting event and without changing view model
this.myForm.get('myInput').setValue(val, {
emitEvent: false,
emitModelToViewChange: false
});
});
}
Run Code Online (Sandbox Code Playgroud)