Angular 5 Pipe, {updateOn:'blur'} not updating model as expected

百般思念 提交于 2021-01-29 19:20:11

问题


I've created a custom pipe in Angular 5 that updates the display of an input field on blur.

The value of the input field is converted and displayed, but the value of the model is not updated properly. This is the functionality I am expecting, is there a way to achieve this with a pipe?

Stackblitz - Link to Sample Code

Steps to Reproduce the issue.

Remove the existing value and type in any number and click outside the field. (Eg: 242235.34234)

The input and the model values do not match.

HTML Code:

<h1>Currency Pipe</h1>

<div>
  Input:
  <input type="text" [ngModel]="inputValue | currency" name="inputValue"
    [ngModelOptions]="{updateOn:'blur'}" (ngModelChange)="inputValue=$event"/>
</div>

<div>{{ inputValue }}</div>

Angular Pipe:

import { Pipe, PipeTransform } from '@angular/core';
import * as accounting from 'accounting';

@Pipe({
  name: 'currency'
})
export class CurrencyPipe implements PipeTransform {

  private format = { precision: 2, thousand: ',', decimal: '.' };

  transform(value: string): any {

    let formattedValue = accounting.unformat(value);
    return accounting.formatNumber(formattedValue, this.format);
  }

}

回答1:


you're adding a pipe for the input but not the output? {{ inputValue | currency }}




回答2:


As i stated before, you shouldn't be using a pipe to morph the value. Instead, try a getter/setter.

import { Component } from '@angular/core';
import * as accounting from 'accounting';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private $inputValue;
  private format = { precision: 2, thousand: ',', decimal: '.' };

  set inputValue(value){
    let formattedValue = accounting.unformat(value);
    this.$inputValue = accounting.formatNumber(formattedValue, this.format);
  } 

  get inputValue(){ return this.$inputValue; }
}

and remove all the pipe stuff from the html.



来源:https://stackoverflow.com/questions/53688946/angular-5-pipe-updateonblur-not-updating-model-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!