【问题标题】:Angular 4 Reactive Form - Value for displayAngular 4 Reactive Form - 显示值
【发布时间】:2018-06-10 12:30:40
【问题描述】:

我正在使用反应形式的方法。我的输入字段具有对应的 formControl 对象,并且在键入时我正在对值进行格式化 - 将所有输入设为大写。

这当然效果很好 - 视图和 formControl 中的值也会更新。

问题是我想将原始值而不是格式化值(大写)发送到服务器

所以我需要一些值,以及在 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)]],
      });
  }

找不到任何帮助。 任何建议将不胜感激。

【问题讨论】:

  • 您的代码看起来如何,您尝试过什么? :)
  • 我用 plunker 更新了问题。问题是我需要在表单控件和服务器中以某种方式进行更新
  • 更准确地说 - 问题是 - 如何格式化输入值而 formContol 值没有格式化
  • 如果这是需要的,为什么还要格式化值?
  • 格式仅用于演示。另一个例子可能是货币管道。逗号和点与模型无关。

标签: angular model-view-controller model reactive-programming form-control


【解决方案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

【讨论】:

  • 当您使用退格时,这将不起作用!但这是个好主意。我学到了很多!谢谢
猜你喜欢
  • 2019-12-26
  • 1970-01-01
  • 2019-03-13
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
相关资源
最近更新 更多