title: Format currency input in angular 2
body: <p>I want to format input to USD currency as you type. The input will have 2 decimal places and will enter from right to left.
  Suppose if I type 54.60 it will be entered as $0.05-->$0.54-->$5.46-->$54.60. This <a href="http://plnkr.co/edit/aNOoxOrDXcnmLPxHmaEp?p=preview" rel="noreferrer">PLUNKER</a> exactly does this, but its in angular js. So far my directive looks like:</p>
  
  <pre><code>import {Directive, Output, EventEmitter} from '@angular/core';
  import {NgControl} from '@angular/forms';
  
  @Directive({
    selector: '[formControlName][currency]',
    host: {
      '(ngModelChange)': 'onInputChange($event)',
      '(keydown.backspace)':'onInputChange($event.target.value, true)'
    }
  })
  export class CurrencyMask {
    constructor(public model: NgControl) {}
  
    @Output() rawChange:EventEmitter&lt;string&gt; = new EventEmitter&lt;string&gt;();
  
    onInputChange(event: any, backspace: any) {
      // remove all mask characters (keep only numeric)
      var newVal = event.replace(/\D/g, '');
      var rawValue = newVal;
      var str = (newVal=='0'?'0.0':newVal).split('.');
      str[1] = str[1] || '0';
      newVal= str[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,') + '.' + (str[1].length==1?str[1]+'0':str[1]);
  
  
  
      // set the new value
      this.model.valueAccessor.writeValue(newVal);
      this.rawChange.emit(rawValue)
    }
  }
  </code></pre>
  
  <p>and in html it is being used as:</p>
  
  <pre><code>&lt;input  name="cost" placeholder="cost" class="form-control"  type="text" currency formControlName="cost" (rawChange)="rawCurrency=$event"&gt;
  </code></pre>
  
  <p><strong>Update:</strong></p>
  
  <p>what finally worked for me is:</p>
  
  <pre><code>onInputChange(event: any, backspace: any) {
      var newVal = (parseInt(event.replace(/[^0-9]/g, ''))/100).toLocaleString('en-US', { minimumFractionDigits: 2 });
      var rawValue = newVal;
  
      if(backspace) {
        newVal = newVal.substring(0, newVal.length - 1);
      }
  
      if(newVal.length == 0) {
        newVal = '';
      }
      else  {
        newVal = newVal;
      }
      // set the new value
      this.model.valueAccessor.writeValue(newVal);
      this.rawChange.emit(rawValue)
    }
  </code></pre>