Angular 4 - How to use currency pipe in input type

♀尐吖头ヾ 提交于 2020-01-01 04:59:40

问题


I have an HTML input:

<input [(ngModel)]="item.value" name="inputField" type="text" />

I want to format its value and use an existing pipe:

.... [(ngModel)]="item.value | currency:'USD':true" .....

Also I'm trying to use it the following way, but it's giving me desirable output for the first time and showing error while updating the field:

<input type="text" 
   [ngModel]="item.value | currency:'USD':true" 
   (ngModelChange)="item.value=($event)">

The above code leads to following error.

ERROR Error: InvalidPipeArgument: '' for pipe 'CurrencyPipe'
at invalidPipeArgumentError (common.es5.js:2610)
at formatNumber (common.es5.js:3176)
at CurrencyPipe.webpackJsonp.../../../common/@angular/common.es5.js.CurrencyPipe.transform (common.es5.js:3350)
at LandingPageComponent.webpackJsonp.../../../../../src/app/guest-handling/landing-page/landing-page.component.ts.LandingPageComponent.transformAmount (landing-page.component.ts:54)
at Object.eval [as handleEvent] (LandingPageComponent.html:38)
at handleEvent (core.es5.js:12014)
at callWithDebugContext (core.es5.js:13475)
at Object.debugHandleEvent [as handleEvent] (core.es5.js:13063)
at dispatchEvent (core.es5.js:8607)
at core.es5.js:9218


回答1:


Here is what worked just fine with currency pipe:

<input matInput type="text" placeholder="Test Price" [ngModel]="testPrice | currency:'USD':'symbol':'2.2'" [ngModelOptions]="{updateOn:'blur'}" 
      (ngModelChange)="testPrice=$event"/>

Basically using the ngModelOptions to update on blur allows for the 0s not to be added while typing in the input field.




回答2:


I think this is a solution for you:

<input type="text" 
   [ngModel]="item.value | currency:'USD':true" 
   (ngModelChange)="item.value=currencyInputChanged($event)">

And then in your controller. Currency mark in from value in input:

  currencyInputChanged(value) {
    var num = value.replace(/[$,]/g, "");
    return Number(num);
  }


来源:https://stackoverflow.com/questions/48321610/angular-4-how-to-use-currency-pipe-in-input-type

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