Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to achieve currency type Input in angular 5?

I want following thing to happen in my angular 5 application.

I am having text box where i am inputting numeric values, as soon as focus of that text box is lost, Numeric values i entered should be formatted to currency with '$' and ',','.' symbols. how to achieve this?

I want to show my input numeric values as in below picture.

enter image description here

like image 818
Harsha Bhat Avatar asked Jan 28 '19 05:01

Harsha Bhat


2 Answers

Here you need CurrencyPipe transform on (blur) event.

In your app.module.ts add CurrencyPipe provider.

import { CommonModule, CurrencyPipe} from '@angular/common';
@NgModule({
  ... 
  providers: [CurrencyPipe]
})
export class AppModule { }

App.component.html

Bind event onblur event to input textbox.

<h1>On Focus lost change Format amount</h1>
<input type="text"(blur)="transformAmount($event)" [(ngModel)]="formattedAmount"  />

In your App.component.ts file write method transformAmount($event)

AppComponent.ts

import { Component,ElementRef } from '@angular/core';
import { CommonModule, CurrencyPipe} from '@angular/common';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
 formattedAmount;
 amount;
   constructor(private currencyPipe : CurrencyPipe) {
  }

   transformAmount(element){
      this.formattedAmount = this.currencyPipe.transform(this.formattedAmount, '$');

      element.target.value = this.formattedAmount;
  }
}

See this Demo

Hope above solution will help you!

like image 143
TheParam Avatar answered Sep 18 '22 17:09

TheParam


Installation - mat currency-format

$ npm i mat-currency-format

Description The directive can be used in html input to automatically change the input to locale currency.

Input in any locale currency convert to number inside the component. On focus the user will see to type in number and on focus out the user will see the number in currency format with the support of internalization format and currency symbol

The selector name of the directive is mvndrMatCurrencyFormat

The directive consists of two inputs:

currencyCode (default value = 'USD') allowNegative (default value = false)

Demo

<input type="text"
      mvndrMatCurrencyFormat
      [allowNegative]="false"
      [currencyCode]="'USD'"
      [value]="usAmount"
      (blur)="updateUSAmount($event)" />

hope this will help, Cheers !

like image 45
Manvender Singh Rathore Avatar answered Sep 17 '22 17:09

Manvender Singh Rathore