title: Angular 2+ Currency Mask
body: <p>I tried a couple of the currency masks out there for Angular 2+ but my requirements don't really fit them so I'm trying to create a Directive myself. Here's what I need:</p>
  
  <ol>
  <li>Allow for null values. Keep the value as a number, not a string.</li>
  <li>On Focus remove currency format. On blur re-format.</li>
  <li>Enter number from right to left (so for $250.00 the user would have to type [2] -> 5 -> 0. (so not starting from the decimal point)</li>
  <li>Don't allow users to type anything but numbers and decimal separator.</li>
  <li>Text-align right</li>
  </ol>
  
  <p>I got most of this working. </p>
  
  <p><strong>The only issue is that it only works on focus/blur/keypress. Since the data is loaded async for my components, no event in the directive is triggered so the initial load of existing dollar amounts isn't formatted.</strong> Here's my Directive so far:</p>
  
  <pre><code>import { Directive, ElementRef, HostListener, Input, AfterViewInit } from '@angular/core';
  import { CurrencyMaskService } from './currency-mask.service';
  
  @Directive({
    selector: '[appCurrencyMask]'
  })
  export class CurrencyMaskDirective implements AfterViewInit {
    private el: HTMLInputElement;
    constructor(private elementRef: ElementRef, private currencyMaskService: CurrencyMaskService) {
      this.el = elementRef.nativeElement;
    }
  
    ngAfterViewInit() {
      this.el.style.textAlign = 'right';
    }
  
    // On Focus remove all non-digit or decimal separator values
    @HostListener('focus', ['$event.target.value'])
    onfocus(value) {
      this.el.value = this.currencyMaskService.parse(value);
    }
  
    // On Blur remove all symbols except last . and set to currency format
    @HostListener('blur', ['$event.target.value'])
    onBlur(value) {
      this.el.value = this.currencyMaskService.transform(value);
    }
  
    // On Blur remove all symbols except last . and set to currency format
    @HostListener('change', ['$event.target.value'])
    onChange(value) {
      this.el.value = this.currencyMaskService.transform(value);
    }
  
    // Prevent user to enter anything but digits and decimal separator
    @HostListener('keypress', ['$event'])
    onKeyPress(event) {
      const key = event.which || event.keyCode || 0;
      if (key !== 46 &amp;&amp; key &gt; 31 &amp;&amp; (key &lt; 48 || key &gt; 57)) {
        event.preventDefault();
      }
    }
  }
  </code></pre>