Custom currency input formatting with simple directives in Angular

Manvender Singh Rathore
2 min readDec 22, 2019

--

What is a directive?

A directive allows you to attach a behavior to DOM elements. This behavior could be as simple or as complex as you’d like.*ngFor and *ngIf are examples of built-in directives in Angular. In this article, I will show you how you can use one of the directive which I had created and published to npm.

One of the most common requirements that keeps popping up during the development of virtually any kind of application is the ability to use custom format for values in specific input fields.

Mat Currency Format

This repos is creating a library for angular currency input and also it is showing how to use the library. This library was generated with Angular CLI version 8.1.3.

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 mvndrCurrencyFormat
  • The directive consists of two inputs: currencyCode (default value = ‘USD’) allowNegative (default value = false)

Demo

  • Demo with Angular material
  • The following steps is required to use this directives:
  • The module need to import
import  {MatCurrencyFormatModule} from 'mat-currency-format';

Inside the view you need to call mvndrMatCurrencyFormat and add input. Below is one of the example

<input type="text"
mvndrMatCurrencyFormat
[allowNegative]="false"
[currencyCode]="'USD'"
[value]="usAmount"
(blur)="updateUSAmount($event)" />
  • Inside the component you can get the value by using event like blur or click or any other event. Below is one of the example updateUSAmount(event) { this.usAmount = event.target.value; }

--

--