0

私は反応型アプローチを使用しています。私は対応するformControlオブジェクトを持っている入力フィールドを持っていますし、入力中に値をフォーマットしています - すべての入力を大文字にします。角4反応性フォーム - ディスプレイの値

もちろん、うまくいく - 値はビューとformControlでも更新されます。

問題は、私は、サーバーに元の値ではなくformmated値(大文字)を送信したいということです

だから私は値、およびformControlオブジェクトの表示のための値のようなものを必要としています。

参照plunker - formatting value formControl

テンプレート:

<input type="text" 
     class="form-control" 
     (blur)="handleOnBlur($event)" 
     (input)="onChange($event)" 
     formControlName="name"> 

モデル:

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)]], 
     }); 
    } 

を助けるために何かを見つけることができません。 ご意見をお待ちしております。

+1

はどのようにあなたのコードを見てのように、あなたは何をしようとしているのでしょうか? :) – Alex

+0

私はplunkerで質問を更新しました。問題は、フォームコントロールとサーバーで何とか更新する必要があることです。 –

+0

より正確に - 問題は - formContol値が書式設定されていないのに、入力値をどのように書式設定できるのですか? –

答えて

1

ここで私の解決策は、data-model-value HTML要素属性を使用してモデル値を格納する方法です。

HTML:

<form [formGroup]="myForm"> 
    <input formControlName="myInput" #inputRef > 
</form> 

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 
    }); 
    }); 
} 

STACKBLITZ:https://stackblitz.com/edit/uppercase-reactive-pipe?file=app%2Fapp.component.ts

+0

@@ Andriy!ありがとう!ビンゴ!!これはまさに私が望んでいたものです –

関連する問題