Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 - How to use currency pipe in input type

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

like image 228
Mahendra Waykos Avatar asked Jan 18 '18 12:01

Mahendra Waykos


People also ask

Can we use pipe in input field Angular?

To use pipes within ngModel on input elements in Angular, we can use separate [(ngModel)] into [ngModel] and (ngModelChange) . to apply the useMyPipeToFormatThatValue pipe to item. value in ngModel . Then we handle our input change events in ngModelChange .

How would you display currency and currency symbol of a country in Angular?

If you want to display your own name instead of default currency symbol you have to pass display parameter. The display parameter can be “code” (currencycode will be displayed) or “symbol” or “symbol-narrow” or any other custom value.

What is the purpose of display property of currency pipe?

CurrencyPipelink. Transforms a number to a currency string, formatted according to locale rules that determine group sizing and separator, decimal-point character, and other locale-specific configurations.


1 Answers

I think you need to combine some answers with a little change like this -

HTML:

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

TS:

updateCurrencyField(value: string): void {
  const onlyNumbers = value.replace(/[^\d.-]/g, '');
  this.valueChange.emit(Number(onlyNumbers));
}
like image 76
oz1985oz Avatar answered Sep 19 '22 19:09

oz1985oz