Friday, 26 April 2019

Angular Directive Example to Format Value to Currency

The following is an example of an Angular 6 directive that format input value to currency when losing focus. It uses NgModel for value binding and CurrencyPipe for the formatter.
import { Directive } from '@angular/core';
import { NgModel } from '@angular/forms';
import { CurrencyPipe } from '@angular/common';

@Directive({
  selector: '[ngModel][my-directive]',
  providers: [NgModel, CurrencyPipe],
  host: {
    '(blur)': 'onInputChange($event)'
  } 
})
export class MyDirective {

  constructor(private model: NgModel, private currencyPipe: CurrencyPipe) { }

  onInputChange($event) {
    var value = $event.target.value;
    if (!value) return;

    var plainNumber: number;
    var formattedValue: string;


    var decimalSeparatorIndex = value.lastIndexOf('.'); 
    if (decimalSeparatorIndex > 0) {
      // if input has decimal part
      var wholeNumberPart = value.substring(0, decimalSeparatorIndex);
      var decimalPart = value.substr(decimalSeparatorIndex + 1);
      plainNumber = parseFloat(wholeNumberPart.replace(/[^\d]/g, '') + '.' + decimalPart)
    } else {
      // input does not have decimal part
      plainNumber = parseFloat(value.replace(/[^\d]/g, ''));
    }

    if (!plainNumber) {
      formattedValue = '';
    }
    else {
      formattedValue = this.currencyPipe.transform(plainNumber.toFixed(2), "USD", "symbol-narrow");
    }

    this.model.valueAccessor.writeValue(formattedValue);
  }
}

Then to use it on HTML part:
<input name="productPrice" [(ngModel)]="price" my-directive />

3 comments:

dean said...

The article provides a practical example of using an Angular directive to format an input value as currency when the field loses focus. The combination of NgModel for value binding and CurrencyPipe for formatting demonstrates how Angular directives can encapsulate reusable behavior while keeping the component code cleaner. The example also shows how the directive processes the entered value, handles decimal portions, converts the input into a numeric value, and writes the formatted currency value back through the model. For developers looking to strengthen their Angular development skills, Angular Online Training can provide a structured path for learning directives, forms, data binding, and other Angular concepts.

dean said...

The use of TypeScript in the directive is another important aspect of the example, particularly through dependency injection of NgModel and CurrencyPipe and the implementation of custom directive logic. Understanding these TypeScript concepts helps developers create reusable Angular components and directives that can be applied across different parts of an application. A TypeScript Online Training program can help learners build the language fundamentals required for working effectively with modern Angular applications.

dean said...

Currency formatting is also a common requirement in real-world applications such as billing forms, product catalogs, payment screens, and financial dashboards. Implementing reusable directives for these requirements provides useful hands-on experience, and Angular Projects can provide opportunities to apply Angular directives, forms, and data-binding concepts within complete application implementations.